美文网首页程序员Android
HttpURLConnection,OkHttp最强解析

HttpURLConnection,OkHttp最强解析

作者: Erich_Godsen | 来源:发表于2020-06-28 23:58 被阅读0次

HttpURLConnection

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

  • 支持GZIP压缩
  • 支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用
  • 在系统层面做了缓存策略处理,加快重复请求的速度

当然,以上几条优点OkHttp也都具备,那为什么还要给大家介绍这个库呢?
因为它比较适合以下场景,如果App调用的接口比较少,参数传递比较简单,我们就没有必要额外再引入一个包去处理网络请求,另外如果是商业使用,还得考虑许可证的问题

常用方法
//设置连接超时时间
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

开源库的地址为:
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")

因为我这边用的是java代码演示,所以版本号我选的是3.14.9,如果是Kotlin,可以引入最新版本4.7.2

同步网络请求
 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");
    }

有什么问题,欢迎大家随时与我交流沟通,谢谢!

相关文章

网友评论

    本文标题:HttpURLConnection,OkHttp最强解析

    本文链接:https://www.haomeiwen.com/subject/cexnfktx.html