Java中发送JSON数据的多种方法与实践**
在现代Web开发中,JSON(JavaScript Object Notation)已成为数据交换的事实标准,Java作为企业级应用开发的主流语言,经常需要将JSON数据发送到服务器或服务端点,本文将详细介绍在Java中发送JSON数据的几种常用方法,涵盖从基础到进阶的场景,并提供代码示例。
准备工作:理解JSON与Java对象的转换
在发送JSON之前,通常需要将Java对象序列化为JSON字符串,或者直接构造JSON字符串,反之,接收方可能需要将JSON字符串反序列化为Java对象,常用的JSON处理库有:
- Jackson:功能强大,性能优异,Spring Framework默认使用。
- Gson:Google开发,API简洁易用。
- org.json:轻量级,API简单。
- Fastjson:阿里巴巴开发,性能卓越,但曾有过安全漏洞,需注意版本。
本文将以Jackson和Gson为例进行讲解,因为它们是目前最流行和推荐的选择。
使用Java原生HttpURLConnection发送JSON
这是最基础的方式,不需要额外依赖,但代码相对繁琐。
步骤:
- 创建URL对象。
- 打开连接,设置请求方法(如POST)。
- 设置请求头(
Content-Type: application/json)。 - 启用输出流。
- 将JSON字符串写入输出流。
- 获取响应码和响应内容。
示例代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonSenderWithHttpUrlConnection {
public static void main(String[] args) {
String targetUrl = "https://example.com/api/resource";
String jsonInputString = "{\"name\":\"John Doe\", \"age\":30, \"email\":\"john.doe@example.com\"}";
try {
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
// 允许输出
connection.setDoOutput(true);
// 写入JSON数据
try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
out.writeBytes(jsonInputString);
out.flush();
}
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
try (BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println("Response: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
优缺点:
- 优点:无需额外库,JDK自带。
- 缺点:代码冗长,处理连接、流、异常等较为繁琐,不适合复杂场景。
使用HttpClient (Java 11+) 发送JSON
Java 11引入了标准的java.net.http.HttpClient,它比HttpURLConnection更现代化、更易用。
步骤:
- 创建HttpClient实例。
- 创建HttpRequest对象,设置方法、URI、头体和JSON体。
- 发送请求并获取HttpResponse。
示例代码:
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 JsonSenderWithHttpClient {
public static void main(String[] args) {
String targetUrl = "https://example.com/api/resource";
String jsonInputString = "{\"name\":\"Jane Doe\", \"age\":25, \"email\":\"jane.doe@example.com\"}";
// 创建HttpClient
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
// 创建HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(targetUrl))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(jsonInputString))
.build();
try {
// 发送请求并获取响应
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
优缺点:
- 优点:现代API,支持HTTP/2,异步请求,代码简洁,是Java 11及以后版本的首选。
- 缺点:需要Java 11或更高版本。
使用第三方HTTP客户端库 (如OkHttp, Apache HttpClient)
这些库提供了更丰富的功能和更便捷的API。
使用OkHttp
Maven依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version> <!-- 请使用最新版本 -->
</dependency>
示例代码:
import okhttp3.*;
import java.io.IOException;
public class JsonSenderWithOkHttp {
public static void main(String[] args) {
String targetUrl = "https://example.com/api/resource";
String jsonInputString = "{\"name\":\"Peter Jones\", \"age\":40, \"email\":\"peter.jones@example.com\"}";
// 创建OkHttpClient
OkHttpClient client = new OkHttpClient();
// 创建请求体
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonInputString, JSON);
// 创建请求
Request request = new Request.Builder()
.url(targetUrl)
.post(body)
.header("Accept", "application/json")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
System.out.println("Response Code: " + response.code());
System.out.println("Response Body: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Apache HttpClient (4.x+)
Maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version> <!-- 请使用最新版本 -->
</dependency>
示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class JsonSenderWithApacheHttpClient {
public static void main(String[] args) {
String targetUrl = "https://example.com/api/resource";
String jsonInputString = "{\"name\":\"Alice Smith\", \"age\":35, \"email\":\"alice.smith@example.com\"}";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(targetUrl);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// 设置请求体
StringEntity entity = new StringEntity(jsonInputString);
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println("Response Body: " + responseBody);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
第三方库共同优缺点:
- 优点:功能强大,API友好,支持连接池、拦截器等高级特性,社区活跃,文档完善。
- 缺点:需要引入外部依赖。
结合Jackson/Gson进行对象到JSON的序列化
在实际开发中,我们通常操作的是Java对象,而不是直接的JSON字符串,这时就需要使用Jackson或Gson将对象序列化为JSON。
使用Jackson序列化并发送
Maven依赖 (Jackson):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version> <!-- 请使用最新版本 -->
</dependency>
示例代码 (结合OkHttp):
import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.*; import java.io.IOException; import java.util.HashMap;



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