sun博客

记录点滴!

HttpUrlConnection系统内置,无须安装。2个同级产品,非继承于HttpUrlConnection。

官网的链接地址为 https://developer.android.google.cn/reference/kotlin/java/net/HttpURLConnection?hl=en
它的主要优点有以下几条

//设置连接超时时间
setConnectTimeout(int)
//设置读取超时时间
setReadTimeout(int)
//设置允许输出(Post必须设置为true)默认false
setDoOutput(boolean);
//设置请求允许输入 默认是true
setDoInput(boolean)
//是否启用缓存(Post请求不能使用缓存)
setUseCaches(boolean)
//设置请求类型
setRequestMethod(String)
//设置请求头
setRequestProperty(String, String)
// Get请求 
 private void httpGet() {
        HttpURLConnection urlConnection= null;
        try {
            URL url = new URL("https://www.baidu.com/");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(3* 1000);
            urlConnection.setReadTimeout(3* 1000);
            urlConnection.setDoOutput(false);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(true);
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("sign", "0x25678");
            urlConnection.connect();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            readStream(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

    }


//post请求
private void httpPost() {
        HttpURLConnection urlConnection= null;
        try {
            URL url = new URL("https://www.baidu.com/");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(3* 1000);
            urlConnection.setReadTimeout(3* 1000);
            //note must be set true
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("sign", "0x25678");
            urlConnection.connect();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            readStream(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

    }

    private void readStream(InputStream in) {
        byte[] buffer = new byte[1024];
        StringBuilder result = new StringBuilder();
        try {
            while (in.read(buffer) != -1) {
                String text = new String(buffer, "utf-8");
                result.append(text);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d(TAG, "read result:" + result.toString());
    }

OkHttp

OkHttp

开源库的地址为:
https://github.com/square/okhttp
4.0及之后的版本为 Kotlin版本,底层用得也是自家库Okio这个库的主要优点如下:

  • 支持HTTP/2,可以合并多个到同一个主机的请求
  • 使用连接池技术减少请求的延迟(如果HTTP/2是不可用)
  • 使用GZIP压缩减少传输的数据量
  • 缓存响应避免重复的网络请求

这些优点大家应该都不陌生,最主要的是这个库使用起来特别方便

引入方式

只要在app路径下build.gradle文件中dependencies项下添加如下依赖即可

implementation("com.squareup.okhttp3:okhttp:3.14.9")
同步网络请求
 private void syncHttp() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://www.baidu.com/")
                .addHeader("sign", "0x123456")
                .build();

        try {
            //同步接口execute
            Response response = client.newCall(request).execute();
            Log.d(TAG, "isSuccessful:" + response.isSuccessful());
            if (response.isSuccessful()) {
                Log.d(TAG, "response:" +response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "requestHttp finish");
    }
异步网络请求
private void asynHttp() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("name", "zhangsan")
                .add("sex", "man")
                .build();

        Request request = new Request.Builder()
                .url("https://www.baidu.com/")
                .addHeader("sign", "0x123456")
                .post(requestBody)
                .build();

        //异步执行,通过enqueue
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure exception:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse body:" + response.body().string());
            }
        });

        Log.d(TAG, "requestHttp finish");
    }

关于Retrofit

https://www.cnblogs.com/guanmanman/p/6085200.html

作者:Erich_Godsen
链接:https://www.jianshu.com/p/87d37ce0e696
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发表评论

邮箱地址不会被公开。 必填项已用*标注