Android中高效发送JSON数据的完整指南
在Android应用开发中,JSON(JavaScript Object Notation)因其轻量级、易读性和与语言无关的特性,成为客户端与服务器交互最常用的数据格式之一,无论是用户登录、数据提交,还是接口调用,都频繁需要将JSON数据通过HTTP请求发送到服务器,本文将详细介绍在Android中发送JSON数据的多种方式,从原生HttpURLConnection到第三方库如OkHttp和Retrofit,并附上完整代码示例,帮助开发者不同场景下的最佳实践。
发送JSON数据的基础流程
无论采用哪种技术方案,发送JSON数据的核心流程基本一致,主要包括以下步骤:
- 准备JSON数据:将Java对象转换为JSON字符串(序列化),或直接构建JSON字符串。
- 创建HTTP请求:初始化HTTP客户端(如HttpURLConnection、OkHttp),设置请求方法(POST/PUT等)、请求头(Content-Type为
application/json)。 - 写入请求体:将JSON字符串作为请求体写入HTTP请求中。
- 发送请求并处理响应:执行请求,读取服务器返回的响应数据(如JSON字符串、状态码等)。
使用原生HttpURLConnection发送JSON
HttpURLConnection是Android SDK内置的HTTP客户端,无需依赖第三方库,适合轻量级或对依赖有严格要求的场景,但它的代码相对冗余,需要手动处理线程、流关闭等细节。
核心步骤
- 开启子线程:网络请求不能在主线程(UI线程)中执行,否则会抛出
NetworkOnMainThreadException。 - 设置请求参数:指定URL、请求方法(POST)、请求头(
Content-Type: application/json)、连接超时等。 - 写入JSON数据:通过
OutputStream将JSON字符串写入请求体。 - 处理响应:通过
InputStream读取服务器返回的数据,并解析结果。
完整代码示例
以下是一个使用HttpURLConnection发送POST请求,提交JSON数据的完整示例:
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "JsonHttpExample";
private static final String API_URL = "https://your-api-endpoint.com/api/data";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendJsonBtn = findViewById(R.id.send_json_btn);
sendJsonBtn.setOnClickListener(v -> sendJsonWithHttpURLConnection());
}
private void sendJsonWithHttpURLConnection() {
// 在子线程中执行网络请求
new Thread(() -> {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 1. 准备JSON数据(这里以简单对象为例)
String jsonInput = "{\"name\":\"张三\",\"age\":25,\"email\":\"zhangsan@example.com\"}";
// 2. 创建URL对象
URL url = new URL(API_URL);
connection = (HttpURLConnection) url.openConnection();
// 3. 设置请求参数
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000); // 连接超时10秒
connection.setReadTimeout(10000); // 读取超时10秒
connection.setDoOutput(true); // 允许输出请求体
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
// 4. 写入JSON数据到请求体
outputStream = connection.getOutputStream();
outputStream.write(jsonInput.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
// 5. 获取响应码
int responseCode = connection.getResponseCode();
Log.d(TAG, "Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
// 6. 读取响应数据
inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
String responseData = response.toString();
Log.d(TAG, "Response Data: " + responseData);
// 在主线程更新UI
runOnUiThread(() -> Toast.makeText(MainActivity.this, "发送成功: " + responseData, Toast.LENGTH_SHORT).show());
} else {
// 请求失败
String errorResponse = readErrorStream(connection.getErrorStream());
Log.e(TAG, "Request Failed: " + errorResponse);
runOnUiThread(() -> Toast.makeText(MainActivity.this, "发送失败: " + responseCode, Toast.LENGTH_SHORT).show());
}
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络异常: " + e.getMessage(), Toast.LENGTH_SHORT).show());
} finally {
// 7. 关闭流和连接
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
Log.e(TAG, "Close OutputStream failed: " + e.getMessage());
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e(TAG, "Close InputStream failed: " + e.getMessage());
}
}
if (connection != null) {
connection.disconnect();
}
}
}).start();
}
// 读取错误流
private String readErrorStream(InputStream errorStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
}
}
注意事项
- 线程处理:网络请求必须在子线程执行,更新UI需切换到主线程(使用
runOnUiThread或Handler)。 - 资源释放:务必关闭
OutputStream、InputStream和HttpURLConnection,避免内存泄漏。 - 字符编码:统一使用
UTF-8编码,避免中文乱码。
使用OkHttp发送JSON
OkHttp是Square公司开源的HTTP客户端,具有高效、简洁、支持异步/同步请求等优势,是目前Android开发中最常用的网络库之一。
添加依赖
在app/build.gradle文件中添加OkHttp依赖:
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.12.0") // 使用最新版本
}
核心步骤
- 创建OkHttpClient:配置超时、拦截器等参数。
- 构建RequestBody:使用
RequestBody.create()将JSON字符串转换为application/json类型的请求体。 - 创建Request:设置URL、方法、请求头和请求体。
- 发送请求:通过
OkHttpClient.newCall()发起同步或异步请求。
完整代码示例
(1)同步请求示例
import okhttp3.*;
import java.io.IOException;
public class OkHttpSyncExample {
private static final String API_URL = "https://your-api-endpoint.com/api/data";
private final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.build();
public void sendJsonSync() {
try {
// 1. 准备JSON数据
String jsonInput = "{\"name\":\"李四\",\"age\":30,\"email\":\"lisi@example.com\"}";
// 2. 创建RequestBody
RequestBody requestBody = RequestBody.create(
jsonInput,
MediaType.parse("application/json; charset=utf-8")
);
// 3. 创建Request
Request request = new Request.Builder()
.url(API_URL)
.post(requestBody)
.header("Accept", "application/json")
.build();
// 4. 发送同步请求
try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseData = response.body().string();
Log.d("OkHttpSync", "Response: " + responseData);
} else {
Log.e("OkHttpSync", "Request failed: " + response.code());
}
}
} catch (IOException e) {
Log.e("OkHttpSync", "IOException: " + e.getMessage());
}
}
}
(2)异步请求示例(推荐)
异步请求不会阻塞线程,适合UI交互场景:
import okhttp3.*;
import java.io.IOException;
public class OkHttpAsyncExample {
private static final String API_URL = "https://your-api-endpoint.com/api/data";
private final OkHttpClient okHttpClient = new OkHttpClient


还没有评论,来说两句吧...