編輯:關於 Android 開發
在 Android 上跟後端打交道的流程,基本上可以拆成兩半:先把資料取回來,再把資料解析成可用的物件。以下這組程式碼把兩件事各自封裝好,只要傳入服務端位址就能取得回應字串。
public static String getHttpText(String url) {
if (MyApplication.FOR_DEBUG) {
Log.i(TAG, "[getHttpText1]" + url);
}
Log.i(TAG, "[getHttpText2]" + url);
if (url == null || url.equals(""))
return null;
StringBuilder builder = new StringBuilder();
InputStreamReader isReader = null;
HttpURLConnection conn = null;
try {
URL u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(TIMEOUT);
if (conn == null || conn.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
conn.connect();
isReader = new InputStreamReader(conn.getInputStream());
BufferedReader reader = new BufferedReader(isReader);
String buffer;
while ((buffer = reader.readLine()) != null) {
builder.append(buffer);
}
reader.close();
return builder.toString();
} catch (Exception e) {
Log.e(TAG, "getHttpText error: " + e.getMessage());
} finally {
if (isReader != null) {
try {
isReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
return null;
}
這段程式有幾個值得留意的細節:以 StringBuilder 逐行累積回應內容,避免大量字串拼接產生的效能問題;用 connectTimeout 設定連線逾時,防止網路不佳時執行緒被無限期阻塞;並在 finally 區塊中確保 reader 與連線一定會被關閉。唯一要補強的是,readLine() 會把換行符號吃掉,若回應內容對換行敏感,改用逐字元讀取會更保險。
取得字串之後,再用 JSONObject 逐層拆解。以下範例示範如何判斷狀態碼、讀取陣列、遍歷元素,並在資料有更新時發送廣播通知介面刷新:
String json = HttpUtils.getHttpText(
Configs.getServerAddress(context)
+ "/api.php/Message/getMessage"
+ Configs.getRoomInfo(context));
if (json == null || json.equals(""))
continue;
try {
JSONObject root = new JSONObject(json);
if (root.getInt("status") != 0)
return;
boolean gotMessage = false;
JSONArray ja = root.getJSONArray("messageList");
int len = ja.length();
long now = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
JSONObject jo = ja.getJSONObject(i);
long deadline = jo.getLong("finish_time") * 1000;
if (deadline <= now) continue;
MarqueeContent content = new MarqueeContent();
content.id = mMarqueeId++;
content.deadline = deadline;
content.text = jo.getString("content");
mMarqueeList.add(content);
gotMessage = true;
}
if (gotMessage) {
context.sendBroadcast(new Intent(MarqueeView.GOT_MARQUEE_ACTION));
}
return;
} catch (JSONException e) {
e.printStackTrace();
}
這裡有幾個實務上很值得沿用的習慣。第一,先檢查 status 再處理業務資料,讓後端的錯誤碼能在最前面被攔下。第二,時間欄位多半以秒為單位傳輸,因此 finish_time 要乘以 1000 才能與 System.currentTimeMillis() 比較,這個小細節漏掉就會導致過期判斷完全失效。第三,只有在真的取得了資料時才發送廣播,可以省下大量無意義的介面刷新。
以上程式以 HttpURLConnection 搭配 org.json 完成,邏輯清楚、無額外依賴,適合小規模或教學用途。若要投入正式專案,可以考慮幾個方向:改用非同步函式庫(如 OkHttp、Retrofit)把請求移出主執行緒並取得攔截器、連線池等能力;把 JSON 解析換成 Gson 或 Moshi,用資料類別對應回應結構,避免大量手寫 getXxx;另外也別忘了為請求加上適當的逾時設定、重試機制與錯誤提示,並在正式環境關閉多餘的 Log 輸出。
Material Design 實作:用 TextInputLayout 做出浮動標籤與錯誤提示
上一篇談完了 NavigationView,這次要說的是表單裡最容易被低估的一個小元件:TextInputLayout。 它解決了什麼問題 TextInputLayou
Android Binder:Service 註冊請求流程解析
Android Binder:Service 註冊請求流程解析 Android 系統大量採用 Service 組件提供核心服務。Service 必須註冊到 Service
硅谷社交 6:添加聯繫人——發送添加好友邀請
硅谷社交 6:添加聯繫人——發送添加好友邀請 添加好友通常分兩步:先「查」,確認對方存在並展示其資料;再「加」,向環信伺服器發出邀請。本篇聚焦發送端的兩個核心按鈕。 一
打造複用標題欄:Android自定義組合控件Titlebar全流程
打造複用標題欄:Android自定義組合控件Titlebar全流程 前言:我一直相信「天生我才必有用」。每個人都有自己的價值,也許那份價值一時之間並不明顯,但請別氣餒——