首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 獲取網絡 JSON 數據並解析顯示:標準流程 - 請求接口 → 解析 JSON → 更新 UI

     編輯:程式設計疑難解答

需求:Android 訪問網絡接口(如新聞、天氣 API)獲取 JSON,解析後在列表/頁面顯示。本文梳理標準異步網絡請求流程,對比 HttpURLConnection、OkHttp、Retrofit 三種主流方案,給出完整代碼模板。

核心流程

  1. 子線程發起 HTTP GET/POST 請求。
  2. 接收響應字符串(JSON 格式)。
  3. 解析 JSON(JSONObject/JSONArray/Gson/Moshi)。
  4. 主線程更新 UI(RecyclerView/ListView/Compose)。
  5. 錯誤處理:網絡異常、解析失敗、空數據、Token 過期。

方案一:OkHttp + Gson(現代主流,推薦)

// 1. 依賴
implementation "com.squareup.okhttp3:okhttp:4.12.0"
implementation "com.google.code.gson:gson:2.10.1"

// 2. 數據類
data class News(val title: String, val url: String, val imageUrl: String)

// 3. 請求與解析
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://api.example.com/news") // 聚合數據等平台申請 Key 後的接口
    .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        runOnUiThread(() -> showError(e.getMessage()));
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String json = response.body().string();
        List<News> list = new Gson().fromJson(json, new TypeToken<List<News>>(){}.getType());
        runOnUiThread(() -> updateRecyclerView(list));
    }
});

方案二:Retrofit + Gson(接口化、解耦、最易維護)

// 接口定義
interface NewsApi {
    @GET("news")
    Call<List<News>> getNews(@Query("key") String apiKey);
}

// 構建
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

NewsApi api = retrofit.create(NewsApi.class);
api.getNews("YOUR_KEY").enqueue(new Callback<List<News>>() {
    @Override public void onResponse(Call<List<News>> call, Response<List<News>> response) {
        if (response.isSuccessful()) updateRecyclerView(response.body());
    }
    @Override public void onFailure(Call<List<News>> call, Throwable t) {
        showError(t.getMessage());
    }
});

方案三:HttpURLConnection(零依賴,教學/極簡項目)

new Thread(() -> {
    try {
        URL url = new URL("https://api.example.com/news?key=YOUR_KEY");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        if (conn.getResponseCode() == 200) {
            String json = new BufferedReader(new InputStreamReader(conn.getInputStream()))
                .lines().collect(Collectors.joining());
            List<News> list = new Gson().fromJson(json, new TypeToken<List<News>>(){}.getType());
            runOnUiThread(() -> updateRecyclerView(list));
        }
    } catch (Exception e) {
        runOnUiThread(() -> showError(e.getMessage()));
    }
}).start();

聚合數據等開放平台接入步驟

  1. 註冊賬號 → 申請「天氣/新聞/笑話」等接口 → 獲取 AppKey。
  2. 2. 閱讀接口文檔:請求 URL、參數、返回 JSON 結構、錯誤碼、頻率限制。 3. 代碼中拼接 URL 或傳參:.url(baseUrl + "?key=" + key)。 4. 解析返回 JSON 結構映射到實體類。

避坑清單

  1. 網絡請求必須在子線程,主線程會拋 NetworkOnMainThreadException。
  2. Android 9+ 預設禁用明文 HTTP,需 android:usesCleartextTraffic="true" 或全站 HTTPS。
  3. JSON 解析用 Gson/Moshi,手寫 JSONObject 易出錯、難維護。
  4. 圖片加載用 Glide/Coil,不要在 Adapter 裡手寫下載邏輯。
  5. 生命週期感知:用 ViewModel + LiveData/Flow 或 LifecycleObserver 取消請求,防內存洩漏。

掌握「OkHttp/Retrofit + Gson + RecyclerView」鐵三角,Android 網絡數據展示功能輕鬆實現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved