OkHttp
简介
OkHttp是时下最火的Http请求框架,其官网及源码地址如下:
- OkHttp官网地址:http://square.github.io/okhttp/
- OkHttp源码地址:https://github.com/square/okhttp
相比于其他网络请求框架,OkHttp有什么优点呢?官方介绍如下:
- HTTP/2 support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if HTTP/2 isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
从上面的介绍我们可以得出有下面这些优点:
- 在Http/2的支持下,如果网络请求的host是同一个时,允许这些请求共用一个socket。
- 使用连接池减少请求延迟。
- 透明的GZIP压缩,减少数据流量。
- 支持响应缓存,避免重复的网络请求。
使用
添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
GET请求
//创建OkHttpClient对象
OkHttpClient httpClient = new OkHttpClient();
//创建Request对象
Request request = new Request.Builder()
.url("http://www.baidu.com")
.addHeader("key", "value")
.get()
.build();
//get方法同步请求
try {
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()){
String result = response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
//get方法异步请求,异步请求的回调方法均在子线程中执行
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//请求成功
String result = response.body().string();
}
});
POST请求