赞
踩
okhttp 3.14.9。OkHttp是Android开发最常用的网络请求框架,由Square公司开源。HttpURLConnection底层实现已经替换成了OKHttp。Retrofit框架底层也是基于OKHttp实现。OkHttp4.x已经改为kotlin实现。Http1、Http2、Quic和WebSocket协议。TCP(Socket),减少请求延时。GZIP,减少数据流量。项目导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
使用时,需要在清单文件AndroidManifest.xml中配置网络使用权限
<uses-permission android:name="android.permission.INTERNET" />

由上图可知,使用OkHttp发起一个请求的具体步骤如下:
OkHttpClient.Builder创建OkHttpClientRequest.Builder创建RequestOkHttpClient对象的newCall方法,传入Request,生成CallCall对象调用execute或者enqueue方法得到响应Response String url="xxx";
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
try {
Response response = call.execute();
Log.d(TAG, response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
String url="xxx";
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).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 {
Log.d(TAG, response.body().string());
}
});
由上述流程和例子可知:
OkHttp发起一次请求时,核心是OkHttpClient、Request和Call三个角色。OkHttpClient、Request的创建使用均由对应的Builder实现(经典的建造者设计模式)。Call对象的execute方法发起的是同步请求,而enqueue方法则是异步请求。Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。