編輯:關於 Android 程式設計
Android 上發網路請求的方式很多,但真正與後端對接時,需要處理的細節比想像中多:編碼、超時、自訂 Header、重試,以及 HTTPS 的憑證驗證。這裡把自己專案裡用的三段程式碼整理出來。
Android SDK 已經把 JSON 相關操作封裝得很好,組 body 很直覺。
/**
* 發送 JSON 格式的 HTTP 請求
* @return 回應的 HTTP 狀態碼
*/
@SuppressLint("DefaultLocale")
public int httpResponseCodeJsonPost(String strUrl, String authorization,
String currentSessionId, String ClientId,
PostParameter[] postParams, String httpMethod) throws SystemException {
int responseCode = -1;
try {
HttpPost request = new HttpPost(strUrl);
JSONObject param = new JSONObject();
for (int j = 0; j < postParams.length; j++) {
param.put(postParams[j].name, postParams[j].value);
}
try {
// 指定 UTF-8,避免中文參數變亂碼
StringEntity se = new StringEntity(param.toString(), "utf-8");
request.setEntity(se);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 連線與讀取超時(毫秒)
request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
// 自訂請求頭
request.setHeader("X-FBox-Session", currentSessionId);
request.setHeader("Authorization", authorization);
request.setHeader("X-FBox-ClientId", ClientId);
request.setHeader("Content-Type", "application/json;charset=UTF-8");
try {
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
// String retSrc = EntityUtils.toString(httpResponse.getEntity()); // 回應內容
responseCode = httpResponse.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
這版改用 HttpURLConnection,並加入了重試機制。
@SuppressLint("DefaultLocale")
public int httpResponseCode(String strUrl, String authorization,
String currentSessionId, String ClientId,
PostParameter[] postParams, String httpMethod) throws SystemException {
int retry = 1;
Response res = null;
int responseCode = -1;
for (int retriedCount = 0; retriedCount < retry; retriedCount++) {
HttpURLConnection con = null;
OutputStream osw = null;
try {
URL url = new URL(strUrl);
con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setRequestProperty("Authorization", authorization);
con.addRequestProperty("X-FBox-ClientId", ClientId);
setHeaders(strUrl, postParams, con, httpMethod);
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
con.setRequestMethod(httpMethod);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
String postParam = "";
if (postParams != null) {
postParam = encodeParameters(postParams);
}
byte[] bytes = postParam.getBytes("UTF-8");
con.setRequestProperty("Content-Length", Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
osw.close();
} else {
con.setRequestMethod(httpMethod);
}
con.setConnectTimeout(this.connectionTimeout);
con.setReadTimeout(this.readTimeout);
res = new Response(con);
responseCode = con.getResponseCode();
} finally {
if (osw != null) {
try { osw.close(); } catch (Exception ignore) { }
}
}
// 攔截逾時並依重試次數決定是否拋出
catch (IOException ioe) {
if (retriedCount == 1) {
throw new SystemException(ioe.getMessage(), ioe, responseCode);
}
}
}
return responseCode;
}
若 URL 是 https,需要多兩步:換成 HttpsURLConnection,並決定如何處理憑證。
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts(); // 信任所有憑證(僅供開發/測試)
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
con = https;
} else {
con = (HttpURLConnection) url.openConnection();
}
配套的信任管理器:
/**
* 信任所有主機——對任何憑證都不做檢查
* Android 採用 X.509 憑證機制
*/
@SuppressLint("TrulyRandom")
private static void trustAllHosts() {
// 建立一個不驗證憑證鏈的信任管理器
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException { }
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException { }
} };
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
上面這段程式碼在網路上到處可見,但它關掉了 HTTPS 的全部保護。使用它,等於允許任何中間人冒充你的伺服器、讀取並竄改所有傳輸內容。它能存在的原因只有一個:讓開發階段可以先用自簽憑證的測試環境跑通。
正式產品請改用以下任一方案:
CertificatePinner 支援這個功能。res/raw,用 KeyStore 載入後組 SSLContext,只信任這一個憑證,而非全部。NetworkOnMainThreadException 從 API 11 就開始拋了,請用 Thread/AsyncTask/OkHttp 的非同步介面。DefaultHttpClient 與 HttpPost 在 API 23 起被從 SDK 中刪除,新專案請直接用 HttpURLConnection 或 OkHttp。retry = 1 其實只跑一次,等於沒重試。實務上建議 2~3 次並搭配指數退避,且只對「連線失敗」重試,4xx 錯誤重試沒有意義。EntityUtils.toString() 之後記得 consume() 或關閉 entity,否則連線無法被連線池複用,會造成 socket 耗盡。
Android 馬賽克效果實作:兩種演算法與效能差距十倍的原因
前陣子看到一個開源專案效果很讚,翻了一下原始碼,思路大致是:在原界面上覆蓋一層自訂 View,取得被點擊那個 View 的內容(Bitmap),在覆蓋層的特定位置畫出來,
自訂控制項實作:以擴展 TextView 為例
自訂控制項有一種常見做法,就是在原生控制項的基礎上進行擴展,例如增加新功能、修改顯示的 UI 等,通常我們可以在 onDraw() 方法中對原生控制項進行擴展與加工。
Android RelativeLayout 對齊與 setPadding 整合技巧
在 Android 版面配置中,常會遇到一個需求:某個文字必須緊跟在另一個文字後面,但当前面的文字太長時,後面的文字仍要完整顯示,而前面的文字則用省略號表示。本文以 Re
重新認識 Android 中的 MVP 架構
前言 為什麼要談 MVP?網路上的討論已經很多,但核心理由其實一句話就能說清:MVC 裡的 Activity 揹了太多不屬於它的責任。當一個類同時負責版面、資料、網路請求