Java发送JSON数据的完整指南
在当今的Web开发中,JSON(JavaScript Object Notation)已成为数据交换的主流格式,Java作为企业级开发的首选语言,经常需要向服务器或其他服务发送JSON数据,本文将详细介绍在Java中如何发送JSON数据的多种方法,包括使用原生Java、第三方库以及流行的HTTP客户端。
使用原生Java发送JSON数据
1 准备JSON数据
我们需要将数据转换为JSON字符串,在Java中,可以使用StringBuilder或字符串拼接来手动构建JSON字符串,但这种方法容易出错且不推荐,更好的方式是使用Java内置的javax.json或其他JSON库。
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
// 创建JSON对象
JsonObject jsonObject = Json.createObjectBuilder()
.add("name", "张三")
.add("age", 30)
.add("email", "zhangsan@example.com")
.build();
// 转换为JSON字符串
String jsonString = jsonObject.toString();
2 使用HttpURLConnection发送POST请求
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonPostExample {
public static void main(String[] args) {
try {
// 1. 创建URL对象
URL url = new URL("https://api.example.com/users");
// 2. 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
// 3. 发送JSON数据
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 4. 获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 5. 处理响应...
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用第三方库发送JSON数据
1 使用Gson库
Google的Gson库是处理JSON的流行选择之一。
添加依赖(Maven):
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
使用示例:
import com.google.gson.Gson;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class GsonJsonPostExample {
public static void main(String[] args) {
// 1. 创建JSON对象
User user = new User("李四", 25, "lisi@example.com");
// 2. 使用Gson转换为JSON字符串
Gson gson = new Gson();
String jsonString = gson.toJson(user);
// 3. 创建HTTP客户端
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
// 4. 创建请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonString))
.build();
try {
// 5. 发送请求并获取响应
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
static class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// getters and setters...
}
}
2 使用Jackson库
Jackson是另一个流行的JSON处理库,性能优异。
添加依赖(Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
使用示例:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class JacksonJsonPostExample {
public static void main(String[] args) {
try {
// 1. 创建对象
User user = new User("王五", 28, "wangwu@example.com");
// 2. 使用Jackson转换为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
// 3. 创建HTTP客户端和请求
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonString))
.build();
// 4. 发送请求
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
static class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// getters and setters...
}
}
使用Spring RestTemplate发送JSON数据
如果你正在使用Spring框架,RestTemplate是发送HTTP请求的便捷选择。
添加依赖(Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
使用示例:
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
public class RestTemplateJsonExample {
public static void main(String[] args) {
// 1. 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 2. 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 3. 创建请求体
User user = new User("赵六", 35, "zhaoliu@example.com");
// 4. 创建HTTP实体(包含请求头和请求体)
HttpEntity<User> request = new HttpEntity<>(user, headers);
// 5. 发送POST请求
String url = "https://api.example.com/users";
String response = restTemplate.postForObject(url, request, String.class);
System.out.println("Response Body: " + response);
}
static class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// getters and setters...
}
}
使用Spring WebClient发送JSON数据
WebClient是Spring 5引入的响应式HTTP客户端,是RestTemplate的现代替代品。
使用示例:
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class WebClientJsonExample {
public static void main(String[] args) {
// 1. 创建WebClient实例
WebClient webClient = WebClient.builder()
.baseUrl("https://api.example.com")
.build();
// 2. 创建请求体
User user = new User("钱七", 40, "qianqi@example.com");
// 3. 发送POST请求
Mono<String> response = webClient.post()
.uri("/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(user)
.retrieve()
.bodyToMono(String.class);
// 4. 阻塞并获取响应
String responseBody = response.block();
System.out.println("Response Body: " + responseBody);
}
static class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// getters and setters...
}
}
最佳实践和建议
- 选择合适的JSON库:根据项目需求选择Gson、Jackson或其他JSON库,Jackson通常提供更好的性能。
- 使用HTTP客户端库:对于复杂的HTTP请求,考虑使用专门的HTTP客户端



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