OkHttp 源码分析

基本使用

  //1. 创建OkHttpClient实例
  OkHttpClient client = new OkHttpClient
                            	.Builder()
                            	.cache(new Cache(new File("cache"), 24 * 1024 * 1024))
                            	.build();
  //2. 创建Request实例                        
	Request request = new Request.Builder().url("http://www.baidu.com").build();
  //3. 创建Call实例  
	Call call = client.newCall(request);
  //4.执行同步请求
	try {
		Response response = call.execute();
		response.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

	//5.执行异步请求
	call.enqueue(new Callback() {

		@Override
		public void onFailure(Call call, IOException e) {
			System.out.println("连接失败");
		}

		@Override
		public void onResponse(Call call, Response response) throws IOException {
			//请求处理,输出结果
			System.out.println(response.body());
		}
});

源码分析

** 创建OkHttpClient实例 **

//建造者设计模式 创建OkHttpClient实例
public OkHttpClient build() {
       return new OkHttpClient(this);
}

** 创建Request请求实体 **

public final class Request {
    final HttpUrl url;
    final String method;
    final Headers headers;
    @Nullable
    final RequestBody body;
    final Object tag;
    private volatile CacheControl cacheControl;
    ...
}
//通过建造者设计模式 创建Request请求实体
Request request = new Request.Builder().url("http://www.baidu.com").build();

** 接下来看看Call的获取 **

Call call = client.newCall(request);

public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false);
}

//创建一个RealCall实例
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
		RealCall call = new RealCall(client, originalRequest, forWebSocket);
		call.eventListener = client.eventListenerFactory().create(call);
		return call;
}

** 执行同步请求execute **

public Response execute() throws IOException {
	synchronized(this) {
		if(this.executed) {
			throw new IllegalStateException("Already Executed");
		}

		this.executed = true;
	}

	this.captureCallStackTrace();
	this.eventListener.callStart(this);

	Response var2;
	try {
    //分发器执行 其实就是直接将请求放到运行请求队列里面去 等会下面有分析这个Dispatcher
		this.client.dispatcher().executed(this);
    //责任链方式 执行链式操作 核心 里面分析
		Response result = this.getResponseWithInterceptorChain();
		if(result == null) {
			throw new IOException("Canceled");
		}

		var2 = result;
	} catch (IOException var7) {
		this.eventListener.callFailed(this, var7);
		throw var7;
	}
	finally {
		this.client.dispatcher().finished(this);
	}

	return var2;
}


** getResponseWithInterceptorChain 方法里面的核心内容 **

Response getResponseWithInterceptorChain() throws IOException {
  //创建一个Interceptor集合列表
	List<Interceptor> interceptors = new ArrayList();
  //加入我们客户端设置的拦截器
	interceptors.addAll(this.client.interceptors());
  //加入retryAndFollowUpInterceptor 负责失败重试以及重定向
	interceptors.add(this.retryAndFollowUpInterceptor);
  //加入BridgeInterceptor 负责把用户构造的请求转换为发送到服务器的请求、把服务器返回的响应转换为用户友好的响应的 。
	interceptors.add(new BridgeInterceptor(this.client.cookieJar()));
  //加入CacheInterceptor 缓存
	interceptors.add(new CacheInterceptor(this.client.internalCache()));
  //加入ConnectInterceptor 建立连接
	interceptors.add(new ConnectInterceptor(this.client));
	if(!this.forWebSocket) {
		interceptors.addAll(this.client.networkInterceptors());
	}
  //CallServerInterceptor 发送和接收数据
	interceptors.add(new CallServerInterceptor(this.forWebSocket));
  //RealInterceptorChain 总得链式处理管理器
	Chain chain = new RealInterceptorChain(interceptors, (StreamAllocation)null, (HttpCodec)null, (RealConnection)null, 0, this.originalRequest, this, this.eventListener, this.client.connectTimeoutMillis(), this.client.readTimeoutMillis(), this.client.writeTimeoutMillis());
  //执行同步请求execute 之后 走完链式的执行拦截器后,返回的最终的结果
	return chain.proceed(this.originalRequest);
}

** 异步执行 enqueue

//RealCall#enqueue
public void enqueue(Callback responseCallback) {
        synchronized(this) {
            if(this.executed) {
                throw new IllegalStateException("Already Executed");
            }

            this.executed = true;
        }

        this.captureCallStackTrace();
        this.eventListener.callStart(this);
        //调用Dispatcher 里面的 enqueue方法
        this.client.dispatcher().enqueue(new RealCall.AsyncCall(responseCallback));
    }

    synchronized void enqueue(AsyncCall call) {
           if(this.runningAsyncCalls.size() < this.maxRequests && this.runningCallsForHost(call) < this.maxRequestsPerHost) {
              //将AsyncCall 放入runningAsyncCallsiebiao里面
               this.runningAsyncCalls.add(call);
               //调用线程池去执行异步请求Call AsyncCall#execute方法
               this.executorService().execute(call);
           } else {
               this.readyAsyncCalls.add(call);
           }

       }

** AsyncCall#execute方法 **

//异步Call
final class AsyncCall extends NamedRunnable {
	private final Callback responseCallback;

	AsyncCall(Callback responseCallback) {
		super("OkHttp %s", new Object[] {RealCall.this.redactedUrl()});
		this.responseCallback = responseCallback;
	}

	String host() {
		return RealCall.this.originalRequest.url().host();
	}

	Request request() {
		return RealCall.this.originalRequest;
	}

	RealCall get() {
		return RealCall.this;
	}

	protected void execute() {
		boolean signalledCallback = false;

		try {
      //还是责任链里面的链式请求操作
			Response response = RealCall.this.getResponseWithInterceptorChain();
      //通过响应的结果进行不同的回调操作
			if(RealCall.this.retryAndFollowUpInterceptor.isCanceled()) {
				signalledCallback = true;
				this.responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
			} else {
				signalledCallback = true;
				this.responseCallback.onResponse(RealCall.this, response);
			}
		} catch (IOException var6) {
			if(signalledCallback) {
				Platform.get().log(4, "Callback failure for " + RealCall.this.toLoggableString(), var6);
			} else {
				RealCall.this.eventListener.callFailed(RealCall.this, var6);
				this.responseCallback.onFailure(RealCall.this, var6);
			}
		}
		finally {
			RealCall.this.client.dispatcher().finished(this);
		}

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章