【网络相关】Where is com.android.okhttp?

Index

  Android 4.4版本开始的网络请求方式HttpURLConnection的HTTP实现部分替换为了OKHttp。以一个网络请求实现为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private String getURLResponse(String urlString){
HttpURLConnection conn = null;
String resultData = "";
try {
URL url = new URL(urlString);
conn = (HttpURLConnection)url.openConnection();
...
} catch (Exception e) {
..
}finally{
...
}
return resultData;
}

  通过URL对象来返回一个HttpURLConnection子类对象来处理网络,查看URL构造函数(/libcore/luni/src/main/java/java/net/URL.java):

1
2
3
4
5
6
7
8
9
10
public URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException {
...
if (streamHandler == null) {
setupStreamHandler();
if (streamHandler == null) {
throw new MalformedURLException("Unknown protocol: " + protocol);
}
}
...
}

  它将会通过setupStreamHandler()来创建数据流处理对象。对比4.4之前版本,http处理类由libcore.net.http.HttpHandler;变为了com.android.okhttp.HttpHandler;https处理类由libcore.net.http.HttpsHandler变为了com.android.okhttp.HttpsHandler。如下图:

okhttp调用

  接下来会发现搜索整个Android源码都搜不到com.android.okhttp.HttpHandler和com.android.okhttp.HttpsHandler。Where is the class?
  还是回到okhttp,会发现/external/okhttp目录下有个文件jarjar-rules.txt:

1
2
rule com.squareup.** com.android.@1
rule okio.** com.android.okio.@1

  可以看到这里通过jarjar规则将包名com.squareup更改为了com.android,因此com.android.okhttp.HttpHandler对应的代码为com.squareup.okhttp.HttpHandler。
  关于jarjar相关介绍可以查看《通过jarjar.jar来替换jar包名的详细介绍》