Android开发使用okhttpGet请求api解析json

owofile Lv5

Android开发使用okhttpGet请求api解析json

案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.example.happy\_deer;
import android.util.Log;
import androidx.annotation.NonNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class UpdateApp {
public static void fetchJsonData() {
OkHttpClient client = new OkHttpClient();
String url = "实际api"; // 替换为你的 API URL
Request request = new Request.Builder()
.url(url)
.build();
// 使用 enqueue 进行异步请求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (response.isSuccessful()){
final String responseBody = response.body().string();
// 在这里处理你的 JSON 数据
parseJson(responseBody);
// 为了更新 UI,记得回到主线程
}else {
Log.e("UpdateApp","无法获取json");
}
}
});
}
public static void parseJson(String responseBody) {
try {
// 将响应体转换为 JSONObject
JSONObject jsonObject = new JSONObject(responseBody);
// 获取 "tag\_name" 的值
String tagName = jsonObject.getString("tag\_name");
// 输出结果
Log.i("TAG", "Tag Name: " + tagName);
} catch (Exception e) {
e.printStackTrace();
}
}
}

tip:需要注意的是,获取到的json在final String responseBody = response.body().string();,我为了拿到自己想要的值,使用官方自带的JSONObject,获取到名为tag_name的数据。

这是我github上发行的APK版本号,目的是为了更新APP。

  • Title: Android开发使用okhttpGet请求api解析json
  • Author: owofile
  • Created at : 2024-09-18 13:52:17
  • Updated at : 2025-04-11 21:18:27
  • Link: https://owofile.github.io/blog/2024/09/18/Android开发使用okhttpGet请求api解析json/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Android开发使用okhttpGet请求api解析json