Android开发使用okhttpGet请求api解析json
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"; Request request = new Request.Builder() .url(url) .build();
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();
parseJson(responseBody);
}else { Log.e("UpdateApp","无法获取json"); } } }); } public static void parseJson(String responseBody) { try {
JSONObject jsonObject = new JSONObject(responseBody);
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。