需求:Android 訪問網絡接口(如新聞、天氣 API)獲取 JSON,解析後在列表/頁面顯示。本文梳理標準異步網絡請求流程,對比 HttpURLConnection、OkHttp、Retrofit 三種主流方案,給出完整代碼模板。
JSONObject/JSONArray/Gson/Moshi)。// 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));
}
});
// 接口定義
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());
}
});
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();
AppKey。.url(baseUrl + "?key=" + key)。
4. 解析返回 JSON 結構映射到實體類。
NetworkOnMainThreadException。android:usesCleartextTraffic="true" 或全站 HTTPS。JSONObject 易出錯、難維護。ViewModel + LiveData/Flow 或 LifecycleObserver 取消請求,防內存洩漏。掌握「OkHttp/Retrofit + Gson + RecyclerView」鐵三角,Android 網絡數據展示功能輕鬆實現。