深入解析OkHttp3

本文深入探讨OkHttp3的特性和使用,包括如何引入、基本使用、封装框架和源码分析。讲解了OkHttp3的网络请求、响应缓存、超时设置以及异步请求等关键功能。此外,还介绍了OkHttp3的内部实现,如Dispatcher的请求调度、Interceptor拦截器机制以及ConnectionPool的连接管理。最后,文章对连接与通信的细节进行了分析。
摘要由CSDN通过智能技术生成

OkHttp是一个精巧的网络请求库,有如下特性:
1)支持http2,对一台机器的所有请求共享同一个socket
2)内置连接池,支持连接复用,减少延迟
3)支持透明的gzip压缩响应体
4)通过缓存避免重复的请求
5)请求失败时自动重试主机的其他ip,自动重定向
6)好用的API

其本身就是一个很强大的库,再加上Retrofit2、Picasso的这一套组合拳,使其愈发的受到开发者的关注。本篇博客,我将对Okhttp3进行分析(源码基于Okhttp3.4)。

如何引入Okhttp3?

配置Okhttp3非常简单,只需要在Android Studio 的gradle进行如下的配置:

 compile 'com.squareup.okhttp3:okhttp:3.4.1'

添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

Okhttp3的基本使用

okHttp的get请求
okHttp的一般使用如下,okHttp默认使用的就是get请求

 String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
    mHttpClient = new OkHttpClient();

    Request request = new Request.Builder().url(url).build();
    okhttp3.Response response = null;
    try {
      
            response = mHttpClient.newCall(request).execute();
            String json = response.body().string();
            Log.d("okHttp",json);
        
    } catch (IOException e) {
        e.printStackTrace();
    }



}

我们试着将数据在logcat进行打印,发现会报错,原因就是不能在主线程中进行耗时的操作
这里写图片描述
说明mHttpClient.newCall(request).execute()是同步的,那有没有异步的方法呢,答案是肯定的,就是mHttpClient.newCall(request).enqueue()方法,里面需要new一个callback我们对代码进行修改,如下

public void requestBlog() {
     String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";

     mHttpClient = new OkHttpClient();

     Request request = new Request.Builder().url(url).build();
/* okhttp3.Response response = null;*/

         /*response = mHttpClient.newCall(request).execute();*/
     mHttpClient.newCall(request).enqueue(new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {

         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
             String json = response.body().string();
             Log.d("okHttp", json);
         }
     });


 }

这里写图片描述

Okhttp的POST请求

POST提交Json数据

private void postJson() throws IOException {
    String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
    String json = "haha";
    
    OkHttpClient client = new OkHttpClient();

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            Log.d(TAG, response.body().string());
        }
    });


}

POST提交键值对
很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。

private void post(String url, String json) throws IOException {
     OkHttpClient client = new OkHttpClient();
     RequestBody formBody = new FormBody.Builder()
             .add("name", "liming")
             .add("school", "beida")
             .build();

     Request request = new Request.Builder()
             .url(url)
             .post(formBody)
             .build();

     Call call = client.newCall(request);
     call.enqueue(new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {

         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
             String str = response.body().string();
             Log.i(TAG, str);

         }

     });
 }


异步上传文件
上传文件本身也是一个POST请求
定义上传文件类型

public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

将文件上传到服务器上:

private void postFile() {
    OkHttpClient mOkHttpClient = new OkHttpClient();
    File file = new File("/sdcard/demo.txt");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

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

添加如下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

提取响应头
典型的HTTP头 像是一个 Map<String, String> :每个字段都有一个或没有值。但是一些头允许多个值,像Guava的Multimap。例如:HTTP响应里面提供的Vary响应头,就是多值的。OkHttp的api试图让这些情况都适用。
当写请求头的时候,使用header(name, value)可以设置唯一的name、value。如果已经有值,旧的将被移除,然后添加新的。使用addHeader(name, value)可以添加多值(添加,不移除已有的)。
当读取响应头时,使用header(name)返回最后出现的name、value。通常情况这也是唯一的name、value。如果没有值,那么header(name)将返回null。如果想读取字段对应的所有值,使用headers(name)会返回一个list。
为了获取所有的Header,Headers类支持按index访问。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
            .url("https://api.github.com/repos/square/okhttp/issues")
            .header("User-Agent", "OkHttp Headers.java")
            .addHeader("Accept", "application/json; q=0.5")
            .addHeader("Accept", "application/vnd.github.v3+json")
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println("Server: " + response.header("Server"));
    System.out.println("Date: " + response.header("Date"));
    System.out.println("Vary: " + response.headers("Vary"));
}

Post方式提交String
使用HTTP POST提交请求到服务。这个例子提交了一个markdown文档到web服务,以HTML方式渲染markdown。因为整个请求体都在内存中,因此避免使用此api提交大文档(大于1MB)。

private void postString() throws IOException {


    OkHttpClient client = new OkHttpClient();


    String postBody = ""
            + "Releases\n"
            + "--------\n"
            + "\n"
            + " * zhangfei\n"
            + " * guanyu\n"
            + " * liubei\n";

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            System.out.println(response.body().string());

        }

    });
   

}

Post方式提交流

以流的方式POST提交请求体。请求体的内容由流写入产生。这个例子是流直接写入Okio的BufferedSink。你的程序可能会使用OutputStream,你可以使用BufferedSink.outputStream()来获取。

public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

private void postStream() throws IOException {
    RequestBody requestBody = new RequestBody() {
        @Override
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n) return factor(x) + " × " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            System.out.println(response.body().string());

        }

    });
}

Post方式提交表单

private void postForm() {
    OkHttpClient client = new OkHttpClient();

    RequestBody formBody = new FormB
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的代码家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值