同步请求
jason
// (1)创建 OkHttpClient 对象OkHttpClient client = new OkHttpClient();
// (2)创建 Request 对象
Request request = new Request.Builder()
.url(url)
.build();
// (3)创建 Call 对象。
Call call = client.newCall(request);
// (4)发送请求并获取服务器返回的数据
Response response = call.execute();
// (5)取出相应的数据
String data = response.body().string();
异步请求
jason
// (1)创建 OkHttpClient 对象OkHttpClient client = new OkHttpClient();
// (2)创建 Request 对象
Request request = new Request.Builder()
.url(url)
.build();
// (3)创建 Call 对象。
Call call = client.newCall(request);
// (4)发送请求并获取服务器返回的数据
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// (5)取出相应的数据
String data = response.body().string();
}
});
简易图
2.1OkHttpClient 对象
OkHttpClient(Builder builder) {
this.dispatcher = builder.dispatcher;
this.proxy = builder.proxy;
this.protocols = builder.protocols;
this.connectionSpecs = builder.connectionSpecs;
this.interceptors = Util.immutableList(builder.interceptors);
this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
this.eventListenerFactory = builder.eventListenerFactory;
this.proxySelector = buil