Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網路請求與 JSON 解析:一套可直接複用的實作

編輯:關於 Android 開發

Android 網路請求與 JSON 解析:一套可直接複用的實作

在 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() 會把換行符號吃掉,若回應內容對換行敏感,改用逐字元讀取會更保險。

二、解析回傳的 JSON

取得字串之後,再用 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 輸出。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved