Java发送JSON数据的完整指南:从基础到实战
在当今的软件开发中,JSON(JavaScript Object Notation)已成为数据交换的主流格式,因其轻量、易读、易解析的特点,被广泛应用于前后端交互、API调用、微服务通信等场景,Java作为企业级开发的核心语言,如何发送JSON数据是开发者的必备技能,本文将详细介绍Java发送JSON数据的多种方式,从原生HttpURLConnection到第三方库(如OkHttp、Apache HttpClient),再到Spring生态的便捷实践,帮助你在不同场景下选择最合适的方案。
发送JSON数据的核心流程
无论采用哪种方式,Java发送JSON数据的核心流程基本一致,主要包括以下步骤:
- 创建HTTP请求:确定请求方法(POST、PUT等,发送JSON数据通常用POST)、请求URL及请求头(需设置
Content-Type: application/json)。 - 构建JSON数据:将Java对象转换为JSON字符串(或直接构造JSON字符串)。
- 设置请求体:将JSON字符串作为请求体写入HTTP请求。
- 发送请求并处理响应:执行请求,获取服务器返回的响应结果(如状态码、响应体)。
使用原生HttpURLConnection发送JSON
HttpURLConnection是Java标准库中提供的HTTP客户端API,无需额外依赖,适合简单的JSON发送需求,但它的代码相对繁琐,需要手动处理连接、流和异常。
示例代码
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class JsonSenderWithHttpUrlConnection {
public static void main(String[] args) throws Exception {
// 1. 目标URL
String urlStr = "https://example.com/api/users";
URL url = new URL(urlStr);
// 2. 创建HTTP连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); // 设置请求方法为POST
connection.setRequestProperty("Content-Type", "application/json"); // 设置请求头
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true); // 允许发送请求体
// 3. 构建JSON字符串(简单示例,实际开发建议用JSON库构建)
String jsonInputString = "{\"name\":\"张三\",\"age\":30,\"email\":\"zhangsan@example.com\"}";
// 4. 发送请求体
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 5. 获取响应
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
try (var br = new java.io.BufferedReader(
new java.io.InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("响应体: " + response.toString());
}
// 6. 关闭连接
connection.disconnect();
}
}
优缺点分析
- 优点:无需依赖第三方库,适合轻量级场景或对依赖有严格限制的项目。
- 缺点:代码冗余(需手动处理流、连接状态),功能有限(不支持连接池、异步请求等)。
使用第三方库发送JSON(推荐)
实际开发中,推荐使用成熟的第三方HTTP客户端库,它们简化了JSON发送的流程,提供了更强大的功能(如连接池、异步请求、JSON序列化/反序列化等),以下是两种主流库的实践:
使用OkHttp发送JSON
OkHttp是Android和Java中最流行的HTTP客户端之一,支持同步/异步请求,内置JSON处理能力,需添加依赖:
Maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
示例代码
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class JsonSenderWithOkHttp {
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) {
// 1. 构建Java对象(实际开发中可能是业务实体)
User user = new User("李四", 25, "lisi@example.com");
try {
// 2. 将Java对象转换为JSON字符串(使用Jackson)
String jsonBody = objectMapper.writeValueAsString(user);
// 3. 构建请求体
RequestBody requestBody = RequestBody.create(
jsonBody,
MediaType.parse("application/json; charset=utf-8")
);
// 4. 构建请求
Request request = new Request.Builder()
.url("https://example.com/api/users")
.post(requestBody)
.addHeader("Accept", "application/json")
.build();
// 5. 发送请求(同步方式)
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println("响应码: " + response.code());
System.out.println("响应体: " + response.body().string());
} else {
System.err.println("请求失败: " + response.code());
}
}
} catch (IOException e) {
System.err.println("发送JSON请求失败: " + e.getMessage());
}
}
// 示例Java对象
static class User {
private String name;
private int age;
private String email;
public User() {} // Jackson需要无参构造器
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter和Setter(省略,实际开发中需添加)
}
}
关键点说明
- JSON转换:使用Jackson的
ObjectMapper将Java对象序列化为JSON字符串(推荐,避免手动拼接JSON)。 - RequestBody:通过
RequestBody.create()方法将JSON字符串封装为请求体,并指定Content-Type。 - OkHttpClient配置:可设置超时时间、重试策略等,支持连接池(默认开启)提升性能。
使用Apache HttpClient发送JSON
Apache HttpClient是另一个成熟的HTTP客户端,功能丰富,适合企业级应用,需添加依赖:
Maven依赖
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 需要Jackson支持JSON序列化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
示例代码
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.StringEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.net.URIBuilder;
import java.net.URI;
import java.util.concurrent.TimeUnit;
public class JsonSenderWithApacheHttpClient {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
// 1. 创建HttpClient(可配置连接池、超时等)
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(10, TimeUnit.SECONDS)
.setConnectionRequestTimeout(10, TimeUnit.SECONDS)
.setResponseTimeout(30, TimeUnit.SECONDS)
.build();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.build()) {
// 2. 构建请求(HttpPost)
URI uri = new URIBuilder("https://example.com/api/users").build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// 3. 构建JSON数据并设置请求体
User user = new User("王五", 28, "wangwu@example.com");
String jsonBody = objectMapper.writeValueAsString(user);
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setEntity(entity);
// 4. 发送请求并处理响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
System.out


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