編輯:關於 Android 程式設計
早些年 Android 上的網絡請求基本只有兩個選擇:Apache 的 HttpClient 與 JDK 自帶的 HttpURLConnection。近幾年 OkHttp 崛起,高版本 SDK 中也把它納入其中。不過官方文檔至今仍推薦使用 HttpURLConnection,並承諾持續維護,所以想真正吃透 Android 網絡層,HttpURLConnection 是繞不過去的一站。
之前畫過一張 HttpURLConnection 與 Socket 的關係圖,本來約好第二天接著寫代碼分析,結果一拖就到了週末晚上。趁著印象還深,把整個源碼追蹤過程記錄下來。本文所有源碼來自 Android 4.0.4,與那張關係圖描述的流程一致,只是這裡講得更細。
先擺一張相關類的結構圖,後面的分析基本都在這個範圍內打轉:

讀源碼之前,腦子裡最好先有一條完整的請求流程。這是一個模擬 POST 表單提交的小例子:
public class EsmTest {
/** 通過 HttpURLConnection 模擬 post 表單提交 */
@Test
public void sendEms() throws Exception {
String wen = "MS2201828";
String btnSearch = "EMS快遞查詢";
URL url = new URL("https://www.kd185.com/ems.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// conn.setConnectTimeout(10000); // 連接超時,單位毫秒
// conn.setReadTimeout(2000); // 讀取超時,單位毫秒
conn.setDoOutput(true); // 需要寫入參數
StringBuffer params = new StringBuffer();
params.append("wen").append("=").append(wen).append("&")
.append("btnSearch").append("=").append(btnSearch);
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes); // 寫入參數
InputStream inStream = conn.getInputStream();
System.out.println(new String(StreamTool.readInputStream(inStream), "gbk"));
}
public void sendSms() throws Exception {
String message = "貨已發到";
message = URLEncoder.encode(message, "UTF-8");
String path = "https://localhost:8083/DS_Trade/mobile/sim!add.do?message=" + message;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
String result = new String(StreamTool.readInputStream(inStream), "UTF-8");
System.out.println(result);
}
}
URL 的構造方法本身幾乎不做實質工作,它把重活交給了一個關鍵角色:URLStreamHandler。
public URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException {
if (spec == null) { throw new MalformedURLException(); }
if (handler != null) { streamHandler = handler; }
spec = spec.trim();
// 取出協議頭,例如 http、https
protocol = UrlUtils.getSchemePrefix(spec);
int schemeSpecificPartStart = protocol != null ? (protocol.length() + 1) : 0;
if (protocol != null && context != null && !protocol.equals(context.protocol)) {
context = null;
}
if (context != null) {
set(context.protocol, context.getHost(), context.getPort(), context.getAuthority(),
context.getUserInfo(), context.getPath(), context.getQuery(), context.getRef());
if (streamHandler == null) { streamHandler = context.streamHandler; }
} else if (protocol == null) {
throw new MalformedURLException("Protocol not found: " + spec);
}
// 重點:準備好對應協議的 StreamHandler
if (streamHandler == null) {
setupStreamHandler();
if (streamHandler == null) {
throw new MalformedURLException("Unknown protocol: " + protocol);
}
}
try {
streamHandler.parseURL(this, spec, schemeSpecificPartStart, spec.length());
} catch (Exception e) {
throw new MalformedURLException(e.toString());
}
}
setupStreamHandler() 的查找順序值得記一下:先查靜態緩存 streamHandlers,緩存沒有就問 streamHandlerFactory;工廠也沒有,再去 java.protocol.handler.pkgs 指定的包下按「協議名 + .Handler」的約定反射加載;全部落空,才會 fallback 到內建的 FileHandler、FtpHandler、HttpHandler、HttpsHandler、JarHandler。找到後一律塞回緩存。
public final class HttpHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new HttpURLConnectionImpl(u, getDefaultPort());
}
@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
if (url == null || proxy == null) { throw new IllegalArgumentException("url == null || proxy == null"); }
return new HttpURLConnectionImpl(url, getDefaultPort(), proxy);
}
@Override
protected int getDefaultPort() { return 80; }
}
所以 url.openConnection() 拿到的其實是 HttpURLConnectionImpl。
無論 GET 還是 POST,都要先建立連接。GET 走 getInputStream(),POST 走 getOutputStream(),兩者都會先觸發連接與引擎初始化。
// POST:先連接,再拿輸出流
@Override
public final OutputStream getOutputStream() throws IOException {
connect();
OutputStream result = httpEngine.getRequestBody();
if (result == null) {
throw new ProtocolException("method does not support a request body: " + method);
} else if (httpEngine.hasResponse()) {
throw new ProtocolException("cannot write request body after response has been read");
}
return result;
}
// GET:拿輸入流,狀態碼 >= 400 直接拋 FileNotFoundException
@Override
public final InputStream getInputStream() throws IOException {
if (!doInput) { throw new ProtocolException("This protocol does not support input"); }
HttpEngine response = getResponse();
if (getResponseCode() >= HTTP_BAD_REQUEST) {
throw new FileNotFoundException(url.toString());
}
InputStream result = response.getResponseBody();
if (result == null) {
throw new IOException("No response body exists; responseCode=" + getResponseCode());
}
return result;
}
getResponse() 是整個請求的心臟,它是一個 while(true) 循環:發請求、讀響應、解析響應頭,如果需要重試就換連接或換方法再來一次,直到 Retry.NONE 才跳出。
private HttpEngine getResponse() throws IOException {
initHttpEngine();
if (httpEngine.hasResponse()) { return httpEngine; }
try {
while (true) {
httpEngine.sendRequest();
httpEngine.readResponse();
Retry retry = processResponseHeaders();
if (retry == Retry.NONE) {
httpEngine.automaticallyReleaseConnectionToPool();
break;
}
String retryMethod = method;
OutputStream requestBody = httpEngine.getRequestBody();
/*
* 雖然 RFC 2616 10.3.2 規定 301 重定向應保持原方法,
* 但 Chrome、Firefox 與 RI 遇到任何重定向都會改用 GET。
*/
int responseCode = getResponseCode();
if (responseCode == HTTP_MULT_CHOICE || responseCode == HTTP_MOVED_PERM
|| responseCode == HTTP_MOVED_TEMP || responseCode == HTTP_SEE_OTHER) {
retryMethod = HttpEngine.GET;
requestBody = null;
}
if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
throw new HttpRetryException("Cannot retry streamed HTTP body", httpEngine.getResponseCode());
}
if (retry == Retry.DIFFERENT_CONNECTION) {
httpEngine.automaticallyReleaseConnectionToPool();
}
httpEngine.release(true);
httpEngine = newHttpEngine(retryMethod, rawRequestHeaders,
httpEngine.getConnection(), (RetryableOutputStream) requestBody);
}
return httpEngine;
} catch (IOException e) {
httpEngineFailure = e;
throw e;
}
}
而 initHttpEngine() 裡藏著一個常被忽略的細節:如果你調用了 setDoOutput(true) 卻把方法設成了 GET,框架會默默把它改成 POST;如果既不是 POST 也不是 PUT,就直接拋 ProtocolException。
private void initHttpEngine() throws IOException {
if (httpEngineFailure != null) { throw httpEngineFailure; }
else if (httpEngine != null) { return; }
connected = true;
try {
if (doOutput) {
if (method == HttpEngine.GET) {
method = HttpEngine.POST; // 要寫入,那這就是一次 POST
} else if (method != HttpEngine.POST && method != HttpEngine.PUT) {
throw new ProtocolException(method + " does not support writing");
}
}
httpEngine = newHttpEngine(method, rawRequestHeaders, null, null);
} catch (IOException e) {
httpEngineFailure = e;
throw e;
}
}
HttpEngine.sendRequest() 承擔兩件事:準備請求頭與 Cookie,以及判斷響應來源。所謂響應來源有三種:CACHE(直接用緩存)、CONDITIONAL_CACHE(發網絡請求,無效時回退緩存)、NETWORK(走網絡)。只有 requiresConnection() 為真時,才會真正去開 Socket。
public final void sendRequest() throws IOException {
if (responseSource != null) { return; }
prepareRawRequestHeaders(); // 填充請求頭與 cookies
initResponseSource(); // 決定 CACHE / CONDITIONAL_CACHE / NETWORK
if (responseCache instanceof HttpResponseCache) {
((HttpResponseCache) responseCache).trackResponse(responseSource);
}
// 只允許讀緩存卻必須走網絡時,用 BAD_GATEWAY_RESPONSE 頂上
if (requestHeaders.isOnlyIfCached() && responseSource.requiresConnection()) {
if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
IoUtils.closeQuietly(cachedResponseBody);
}
this.responseSource = ResponseSource.CACHE;
this.cacheResponse = BAD_GATEWAY_RESPONSE;
RawHeaders rawResponseHeaders = RawHeaders.fromMultimap(cacheResponse.getHeaders());
setResponse(new ResponseHeaders(uri, rawResponseHeaders), cacheResponse.getBody());
}
if (responseSource.requiresConnection()) {
sendSocketRequest(); // 走 socket
} else if (connection != null) {
HttpConnectionPool.INSTANCE.recycle(connection);
connection = null;
}
}
private void sendSocketRequest() throws IOException {
if (connection == null) { connect(); }
if (socketOut != null || requestOut != null || socketIn != null) {
throw new IllegalStateException();
}
socketOut = connection.getOutputStream();
requestOut = socketOut;
socketIn = connection.getInputStream();
if (hasRequestBody()) { initRequestBodyOut(); }
}
再往下是 HttpConnection.connect()。它的策略順序很清楚:先看有沒有指定代理,沒有就問系統 ProxySelector;對每個候選代理逐一嘗試,失敗則通過 connectFailed() 告知選擇器;全部不行才建立直連。無論走哪條路,最終都會落到 HttpConnectionPool 手上。
public static HttpConnection connect(URI uri, Proxy proxy, boolean requiresTunnel, int connectTimeout)
throws IOException {
if (proxy != null) {
Address address = (proxy.type() == Proxy.Type.DIRECT)
? new Address(uri) : new Address(uri, proxy, requiresTunnel);
return HttpConnectionPool.INSTANCE.get(address, connectTimeout);
}
ProxySelector selector = ProxySelector.getDefault();
List<Proxy> proxyList = selector.select(uri);
if (proxyList != null) {
for (Proxy selectedProxy : proxyList) {
if (selectedProxy.type() == Proxy.Type.DIRECT) { continue; }
try {
Address address = new Address(uri, selectedProxy, requiresTunnel);
return HttpConnectionPool.INSTANCE.get(address, connectTimeout);
} catch (IOException e) {
selector.connectFailed(uri, selectedProxy.address(), e);
}
}
}
return HttpConnectionPool.INSTANCE.get(new Address(uri), connectTimeout);
}
連接池的複用邏輯也不算複雜:先按 Address 找到隊列,從隊尾開始挑一個還沒失效(isStale() 為假)的連接重複使用,一個合適的都沒有就新建。而 DNS 解析與 Socket 連接發生在 HttpConnection 的構造過程中——InetAddress.getAllByName() 拿到所有 IP,然後逐個 connect(),成功即 break,全部失敗才拋出最後一個異常。
public HttpConnection get(HttpConnection.Address address, int connectTimeout) throws IOException {
// 先嘗試複用現有連接
synchronized (connectionPool) {
List<HttpConnection> connections = connectionPool.get(address);
if (connections != null) {
while (!connections.isEmpty()) {
HttpConnection connection = connections.remove(connections.size() - 1);
if (!connection.isStale()) {
final Socket socket = connection.getSocket();
SocketTagger.get().tag(socket); // socket 被複用,重新打標
return connection;
}
}
connectionPool.remove(address);
}
}
// 沒有可複用的,新建
return address.connect(connectTimeout);
}
readResponse() 的職責順序是:補寫請求頭 → 刷請求體 → flush → 解析響應頭 → 判斷是否命中條件緩存 → 準備響應體流。響應體的讀取方式取決於響應頭:chunked 用 ChunkedInputStream,有 Content-Length 用 FixedLengthInputStream,兩者都沒有就用 UnknownLengthHttpInputStream 一直讀到流結束。若開啟了透明 gzip,還會再包一層 GZIPInputStream。
public final void readResponse() throws IOException {
if (hasResponse()) { return; }
if (responseSource == null) {
throw new IllegalStateException("readResponse() without sendRequest()");
}
if (!responseSource.requiresConnection()) { return; }
if (sentRequestMillis == -1) {
int contentLength = requestBodyOut instanceof RetryableOutputStream
? ((RetryableOutputStream) requestBodyOut).contentLength() : -1;
writeRequestHeaders(contentLength);
}
if (requestBodyOut != null) {
requestBodyOut.close();
if (requestBodyOut instanceof RetryableOutputStream) {
((RetryableOutputStream) requestBodyOut).writeToSocket(requestOut);
}
}
requestOut.flush();
requestOut = socketOut;
readResponseHeaders();
responseHeaders.setLocalTimestamps(sentRequestMillis, System.currentTimeMillis());
if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
if (cachedResponseHeaders.validate(responseHeaders)) {
if (responseCache instanceof HttpResponseCache) {
((HttpResponseCache) responseCache).trackConditionalCacheHit();
}
release(true);
setResponse(cachedResponseHeaders.combine(responseHeaders), cachedResponseBody);
return;
} else {
IoUtils.closeQuietly(cachedResponseBody);
}
}
if (hasResponseBody()) {
maybeCache(); // 可重入,會調用戶代碼
}
initContentStream(getTransferStream());
}
private InputStream getTransferStream() throws IOException {
if (!responseSource.requiresConnection()) { ... }
if (!hasResponseBody()) {
return new FixedLengthInputStream(socketIn, cacheRequest, this, 0);
}
if (responseHeaders.isChunked()) {
return new ChunkedInputStream(socketIn, cacheRequest, this);
}
if (responseHeaders.getContentLength() != -1) {
return new FixedLengthInputStream(socketIn, cacheRequest, this, responseHeaders.getContentLength());
}
return new UnknownLengthHttpInputStream(socketIn, cacheRequest, this);
}
整條鏈路串下來大概是這樣:URL 解析出協議 → 找到對應的 URLStreamHandler → 生成 HttpURLConnectionImpl → 初始化 HttpEngine 並決定響應來源 → 從連接池取或新建 Socket → 寫請求頭與請求體 → 讀響應頭並選擇合適的流 → 交給上層消費。
其中路由信息獲取、DNS 解析與緩存、緩存過期策略這幾塊我還沒細讀,但光是這些也夠消化一陣子了。相信回頭再看 OkHttp 的實現,會順暢很多。
夜深了。默默肅立的路燈像等待檢閱的哨兵,站姿筆挺,睜著炯炯有神的眼睛,時刻守護這城市的安寧。一排排、一行行路燈向遠方延伸,匯聚成一支支流光溢彩的河流,偶爾有汽車疾馳而過,也像一尾尾魚兒在河裡游動。
Android Studio 2.2.2 配置 NDK:從安裝到產出 so 的完整步驟
環境說明 作業系統:Windows 7 開發工具:Android Studio 2.2.2 Android Studio 從 2.2 起改用實驗性的 ex
Cocos2D-x 遊戲開發:CCMoveTo、CCMoveBy、CCScaleTo 與 CCBlink
歇了兩三天,是不是感覺我沒什麼恆心啊?沒關係,今天咱們繼續!本文要學習的是 CCMoveTo、CCMoveBy、CCScaleTo、CCBlink 這四個動作類,它們都比
Android EditText 為什麼只剩下面一條橫線?改回傳統樣式的方法
從 Android 4.0 開始,EditText 的預設外觀被換成了 Material 之前的「只有底線」風格——輸入框本身完全透明,只在下方留一條細線。做的時候覺得很
Android 開發:用 MediaRecorder 錄製音訊
要在 Android 應用中錄音,Android 提供了 MediaRecorder 類別。關於它的完整 API 說明可參考《Android 開發之 MediaRecor