Android OkHttp使用和源码详解,flutter跳转到appstore

.cache(cache);      //设置缓存Request request = new Request.Builder().url(url).build();builder.build().newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call 
摘要由CSDN通过智能技术生成

.cache(cache);      //设置缓存

Request request = new Request.Builder()

.url(url)

.build();

builder.build().newCall(request).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {}

@Override

public void onResponse(Call call, Response response) throws IOException {}

});

}

请求操作的起点从 OkHttpClient.newCall().enqueue() 方法开始

OkHttpClient.newCall


@Override public Call newCall(Request request) {

return RealCall.newRealCall(this, request, false /* for web socket */);

}

RealCall.newRealCall.java

static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {

// Safely publish the Call instance to the EventListener.

RealCall call = new RealCall(client, originalRequest, forWebSocket);

call.transmitter = new Transmitter(client, call);

return call;

}

这个方法会返回一个 RealCall 对象,通过它将网络请求操作添加到请求队列中。

RealCall.enqueue


@Override public void enqueue(Callback responseCallback) {

synchronized (this) {

if (executed) throw new IllegalStateException(“Already Executed”);

executed = true;

}

transmitter.callStart();

client.dispatcher().enqueue(new AsyncCall(responseCallback));

}

client.dispatcher()返回Dispatcher,调用 Dispatcher 的 enqueue 方法,执行一个异步网络请求的操作。

Dispatcher 是 OkHttpClient 的调度器,是一种门户模式。主要用来实现执行、取消异步请求操作。本质上是内部维护了一个线程池去执行异步操作,并且在 Dispatcher 内部根据一定的策略,保证最大并发个数、同一 host 主机允许执行请求的线程个数等。

Dispatcher.enqueue


void enqueue(AsyncCall call) {

synchronized (this) {

readyAsyncCalls.add(call);

if (!call.get().forWebSocket) {

AsyncCall existingCall = findExistingCallWithHost(call.host());

if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);

}

}

promoteAndExecute();

}

实际上就是使用线程池执行了一个 AsyncCall,而 AsyncCall 继承了 NamedRunnable,NamedRunnable 实现了 Runnable 接口,因此整个操作会在一个子线程(非 UI 线程)中执行。

NamedRunnable


/**

* Runnable implementation which always sets its thread name.

*/

public abstract class NamedRunnable implements Runnable {

protected final String name;

public NamedRunnable(String format, Object… args) {

this.name = Util.format(format, args);

}

@Override public final void run() { <

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值