HttpClient 相當於輕量級瀏覽器,內含連線池、Cookie Store、認證快取。全 App 共用單一實例可複用連線、減少資源消耗、統一配置。
public class CustomerHttpClient {
private static final String CHARSET = HTTP.UTF_8;
private static HttpClient client;
private CustomerHttpClient() {}
public static synchronized HttpClient getHttpClient() {
if (client == null) {
HttpParams params = new BasicHttpParams();
// 協議版本
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params,
"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build.FRG83) " +
"AppleWebKit/553.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
// 三種超時區別
ConnManagerParams.setTimeout(params, 1000); // 從連線池取連線超時
HttpConnectionParams.setConnectionTimeout(params, 2000); // 建立 Socket 連線超時
HttpConnectionParams.setSoTimeout(params, 4000); // 讀取資料超時
// 支援 HTTP/HTTPS
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// 執行緒安全連線管理器
ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry);
client = new DefaultHttpClient(mgr, params);
}
return client;
}
}
| 超時類型 | 參數 | 含義 | 例外 |
|---|---|---|---|
| 連線池取連線 | 從 ThreadSafeClientConnManager 取得可用連線的最長等待時間 | ConnectionPoolTimeoutException | |
| 建立連線 | TCP 三向交握、SSL 握手完成的最長時間 | ConnectTimeoutException | |
| 讀取資料 | Socket 等待伺服器回傳資料的最長時間 | SocketTimeoutException |
public static String post(String url, NameValuePair... params) {
try {
List form = new ArrayList<>();
for (NameValuePair p : params) form.add(p);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, CHARSET);
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpResponse resp = getHttpClient().execute(request);
if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("請求失敗: " + resp.getStatusLine().getStatusCode());
}
HttpEntity resEntity = resp.getEntity();
return resEntity != null ? EntityUtils.toString(resEntity, CHARSET) : null;
} catch (UnsupportedEncodingException | ClientProtocolException e) {
Log.w(TAG, e);
return null;
} catch (IOException e) {
throw new RuntimeException("連線失敗", e);
}
}
String url = "https://api.example.com/adduser";
NameValuePair p1 = new BasicNameValuePair("username", "張三");
NameValuePair p2 = new BasicNameValuePair("password", "123456");
try {
String json = CustomerHttpClient.post(url, p1, p2);
JSONObject obj = new JSONObject(json);
int userId = obj.getInt("userid");
Log.i(TAG, "新用戶 ID: " + userId);
} catch (RuntimeException e) {
// 網路/HTTP 錯誤
} catch (JSONException e) {
// 解析錯誤
}
HttpURLConnection 或 OkHttp / Retrofit。掌握 HttpClient 封裝精髓,為遷移現代網路庫打下堅實基礎。