okhttp

来源:互联网 发布:acm编程规则 编辑:程序博客网 时间:2024/06/09 16:25

《1》

Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。

OkHttp是一个高效的HTTP库:

  • 支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求

  • 如果SPDY不可用,则通过连接池来减少请求延时

  • 无缝的支持GZIP来减少数据流量

  • 缓存响应数据来减少重复的网络请求

①首先导入依赖,最新的版本是3.4.1,在gradle中:

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

OKHttp内部依赖Okio库,所以也要添加Okio库,最新版本为1.9.0:

compile 'com.squareup.okio:okio:1.9.0'

②发送HTTP请求 
GET请求

//得到OKHttpClient对象OkHttpClient okHttpClient=new OkHttpClient();//得到Request对象Request request=new Request.Builder()                .url("http://api.36wu.com/Weather/GetWeather?district=%E5%8C%97%E4%BA%AC")                .build();//OkhttpClient#newCall()得到Call对象Call call=okHttpClient.newCall(request);//Call#enqueue()请求网络call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                Log.e("fail",e.toString());            }            @Override            public void onResponse(Call call, Response response) throws IOException{                Log.e("success",response.body().toString());            }        });    }




2.2.1,同步网络请求

我们首先看 RealCall#execute

复制代码
@Override public Response execute() throws IOException {  synchronized (this) {    if (executed) throw new IllegalStateException("Already Executed");  // (1)    executed = true;  }  try {    client.dispatcher().executed(this);                                 // (2)    Response result = getResponseWithInterceptorChain();                // (3)    if (result == null) throw new IOException("Canceled");    return result;  } finally {    client.dispatcher().finished(this);                                 // (4)  }}
复制代码

 

这里我们做了 4 件事:

  1. 检查这个 call 是否已经被执行了,每个 call 只能被执行一次,如果想要一个完全一样的 call,可以利用 call#clone 方法进行克隆。
  2. 利用 client.dispatcher().executed(this) 来进行实际执行,dispatcher 是刚才看到的OkHttpClient.Builder 的成员之一,它的文档说自己是异步 HTTP 请求的执行策略,现在看来,同步请求它也有掺和。
  3. 调用 getResponseWithInterceptorChain() 函数获取 HTTP 返回结果,从函数名可以看出,这一步还会进行一系列“拦截”操作。
  4. 最后还要通知 dispatcher 自己已经执行完毕。

原创粉丝点击