1. HttpUrlConnection / HttpClient / OkHttp 都是Android 网络通信的类库。
  2. HttpClient是Apache基金会下的开源网络库,功能强大,API众多。正是因为API极多,很难兼容情况下升级维护,因此Android团队在提升优化httpClient方面的工作态度不积极。
  3. HttpUrlConnection是一款轻量级Http客户端,提供的API比较简单,容易使用和扩展。
  4. OkHttp功能更强大,不仅具有高效的请求效率,并且提供了很多开箱即用的网络疑难杂症的解决方案。
  5. Android 5.1 即API 22 弃用 HttpClient ; Android 6.0 即API 23 移除Apache HTTP Client ; 并推荐使用HttpUrlConnection。
  6. 从Android 4.4起,HttpUrlConnection内部实现使用OkHttp

HttpUrlConnection通信流程:

HttpUrlConnection对象的获取方式:

  • 通过URL构造获得
->URL url = new URL(String uri);
transient URLStreamHandler handler;

public URL(){
    ......
    static URLStreamHandler getURLStreamHandler(String protocol) {
    ...... 
   } else if (protocol.equals("http")) {
                        handler = (URLStreamHandler)Class.
                            forName("com.android.okhttp.HttpHandler").newInstance();
    } else if (protocol.equals("https")) {
                        handler = (URLStreamHandler)Class.
                            forName("com.android.okhttp.HttpsHandler").newInstance();
}

    ......
}

-> HttpURLConnection con = (HttpURLConnection) url.openConnection();

->public URLConnection openConnection() throws java.io.IOException {
        return handler.openConnection(this);
    }

-> @Override protected URLConnection openConnection(URL url) throws IOException {
        return newOkUrlFactory(null /* proxy */).open(url);
    }
-> public HttpURLConnection open(URL url) {
    return open(url, client.getProxy());
  }
  HttpURLConnection open(URL url, Proxy proxy) {
    String protocol = url.getProtocol();
    OkHttpClient copy = client.copyWithDefaults();
    copy.setProxy(proxy);
    if (protocol.equals("http")) return new HttpURLConnectionImpl(url, copy);
    if (protocol.equals("https")) return new HttpsURLConnectionImpl(url, copy);
    throw new IllegalArgumentException("Unexpected protocol: " + protocol);
  }
  • 通过NetWork对象获取

why "com.android.okhttp" not "com.squareup.okhttp"?

jarjar.txt-https://android.googlesource.com/platform/external/okhttp/+/master/jarjar-rules.txt

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

HttpHandler的openConnection()实现:

Android 6.0 newOkUrlFactory(null /* proxy */).open(url);

https://gitlab.com/Codeaurora/platform_external_okhttp/blob/android-6.0.1_r56/android/main/java/com/squareup/okhttp/HttpHandler.java

newOkHttpClient(null /* proxy */).open(url); //Android 不知道什么版本

https://android.googlesource.com/platform/external/okhttp/+/54a6fb9990ddb2ab66d4afc79541a0801b1aaac9/android/main/java/com/squareup/okhttp/HttpHandler.java

OKUrlFactory :

https://android.googlesource.com/platform/external/okhttp/+/6c251e2/okhttp-urlconnection/src/main/java/com/squareup/okhttp/OkUrlFactory.java

HttpURLConnectionImpl:

https://android.googlesource.com/platform/external/okhttp/+/2946265382960fbd8e2bd765e40e3bc7016e960e/src/main/java/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java

results matching ""

    No results matching ""