OkHttp详解

HTTP是现代应用的网络方式。我们用其交换数据和媒体。高效地执行HTTP使您的数据加载速度更快并节省带宽。

OKHTTP无疑是一个有效的HTTP客户端:

  • 支持HTTP/2,允许同一个主机的请求(request)共享一个socket
  • 如果HTTP/2不可用,连接池也可以减少请求延迟
  • 使用GZIP缩小下载数据的大小
  • 响应缓存避免重复的网络请求

当网络出现问题时,OKHTTP会从常见的连接问题中自动恢复。如果您的服务具有多个IP地址,如果第一连接失败,OKHTTP将尝试替换地址。这对于IPv4+IPv6和托管在冗余数据中心的服务来说是必需的。OKHTTP启动与现代TLS特性(SNI,ALPN)的新连接,如果握手失败,则返回到TLS 1.0。

使用OkHttp很简单。它的请求/响应API是用Builder设计的。它支持同步阻塞调用和带有回调的异步调用。

OkHttp支持Android 2.3 以上版本,jdk最低版本1.7。

OkHttp的使用:

可以下载jar包或者查看Github源码

Maven


  com.squareup.okhttp3
  okhttp
  3.10.0

Gradle

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

如果你的代码启用了混淆

-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
-dontwarn org.conscrypt.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

简单的同步请求获取String的例子:

Get请求

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

Post请求

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

异步获取String的例子:

Get请求

    OkHttpClient client=new OkHttpClient();
    public void run(String url){
        Request request = new Request.Builder()
                .url(url)
                .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 {
                //回调结果
                String str=response.body().string();
            }
        });
    }

Post请求

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client=new OkHttpClient();
    public void run(String url,String json){
        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 {
                //回调结果
                String str=response.body().string();
            }
        });
    }

以上就是OkHttp的简单用法。点击查看OkHttpClient介绍。



你可能感兴趣的:(android)