当前位置:首页 > 行业动态 > 正文

安卓向服务器请求json

安卓客户端通过HttpURLConnection/OkHttp发起HTTP请求,服务器返回JSON格式数据,客户端使用Gson/Jackson解析 JSON,转换为Java对象供业务逻辑处理

安卓向服务器请求JSON的实现步骤


配置网络权限

AndroidManifest.xml 中添加网络访问权限:

<uses-permission android:name="android.permission.INTERNET" />

选择网络请求库

  • OkHttp:轻量级、高效的 HTTP 客户端。
  • Retrofit:基于 OkHttp 的高级封装,支持注解和自动 JSON 解析。

使用 OkHttp 发起请求(同步/异步)

1 同步请求(不推荐,可能阻塞主线程)

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://api.example.com/data")
        .build();
try (Response response = client.newCall(request).execute()) {
    if (response.isSuccessful()) {
        String jsonData = response.body().string();
        // 解析 JSON 数据
    } else {
        // 处理错误(如 404、500)
    }
} catch (IOException e) {
    e.printStackTrace();
}

2 异步请求(推荐)

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://api.example.com/data")
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败(如网络错误)
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String jsonData = response.body().string();
            // 解析 JSON 数据(需切换到主线程更新 UI)
        } else {
            // 处理 HTTP 错误(如 404、500)
        }
    }
});

解析 JSON 数据

1 使用 JSONObjectJSONArray

String jsonData = "{"name":"John", "age":30}";
try {
    JSONObject jsonObject = new JSONObject(jsonData);
    String name = jsonObject.getString("name");
    int age = jsonObject.getInt("age");
} catch (JSONException e) {
    e.printStackTrace();
}

2 使用 Gson 库(推荐)

添加依赖(build.gradle):

安卓向服务器请求json  第1张

implementation 'com.google.code.gson:gson:2.10.1'

定义数据类:

public class User {
    private String name;
    private int age;
    // Getter 和 Setter
}

解析 JSON:

Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);

在主线程更新 UI

异步请求的回调中,如果需要更新 UI,需切换到主线程:

@Override
public void onResponse(Call call, Response response) throws IOException {
    final String jsonData = response.body().string();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // 更新 UI(如 TextView、RecyclerView)
        }
    });
}

错误处理

  • 网络错误:检查 IOExceptiononFailure 回调。
  • JSON 格式错误:捕获 JSONException
  • HTTP 错误码:通过 response.code() 判断。

常见问题与解答

问题 解答
Q1:如何在子线程中更新 UI? 使用 runOnUiThread()Handler 将操作切换到主线程。
runOnUiThread(() -> textView.setText("更新内容"));
Q2:如何发送带参数的 POST 请求? 使用 OkHttp 的 FormBodyRequestBody
java<br>RequestBody body = new FormBody.Builder()<br> .add("key1", "value1")<br> .add("key2", "value2")<br> .build();<br>Request request = new Request.Builder()<br> .url("https://api.example.com/post")<br> .post(body)<br> .build();<br>client.newCall(request).enqueue(callback);<br>

完整示例代码(OkHttp + Gson)

// 1. 添加权限
// <uses-permission android:name="android.permission.INTERNET" />
// 2. 依赖(build.gradle)
// implementation 'com.squareup.okhttp3:okhttp:4.11.0'<br>// implementation 'com.google.code.gson:gson:2.10.1'
// 3. 数据类
public class User {
    private String name;
    private int age;
    // Getter 和 Setter
}
// 4. 异步请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://api.example.com/user")
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // 处理失败
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String jsonData = response.body().string();
            Gson gson = new Gson();
            User user = gson.fromJson(jsonData, User.class);
            // 切换到主线程更新 UI
            runOnUiThread(() -> textView.setText(user.getName()));
        } else {
            // 处理错误
        }
    }
});
0