Java后台发送JSON的多种实现方式详解
在现代Web开发中,JSON(JavaScript Object Notation)因其轻量级、易读性和跨语言特性,已成为前后端数据交互的主流格式,Java作为企业级应用开发的核心语言,后台发送JSON数据的需求极为常见——无论是RESTful API的响应、第三方接口的调用,还是微服务之间的通信,都离不开JSON数据的传递,本文将详细介绍Java后台发送JSON的多种实现方式,从原生HttpURLConnection到主流框架(如Spring Boot、OkHttp、Apache HttpClient),并提供完整代码示例,帮助开发者根据实际场景选择最合适的方案。
使用原生HttpURLConnection发送JSON
HttpURLConnection是Java标准库(java.net包)提供的HTTP客户端API,无需额外依赖,适合轻量级或对依赖有严格要求的场景,其核心步骤包括:创建连接、设置请求头、写入JSON数据、读取响应。
示例代码:POST请求发送JSON
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionJsonSender { public static void main(String[] args) { String targetUrl = "https://example.com/api/resource"; String jsonInput = "{\"name\":\"张三\",\"age\":30,\"city\":\"北京\"}"; try { // 1. 创建URL对象 URL url = new URL(targetUrl); // 2. 打开连接( HttpURLConnection默认是GET请求,需手动设置POST) 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 (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.write(jsonInput.getBytes("UTF-8")); out.flush(); } // 4. 获取响应码 int responseCode = connection.getResponseCode(); System.out.println("响应码: " + responseCode); // 5. 读取响应数据 StringBuilder response = new StringBuilder(); try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), "UTF-8"))) { String line; while ((line = in.readLine()) != null) { response.append(line); } } System.out.println("响应内容: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } }
关键点说明
- 请求头设置:
Content-Type: application/json
告知服务器请求体是JSON格式;Accept: application/json
声明期望接收JSON响应。 - DoOutput:
connection.setDoOutput(true)
必须调用,否则无法写入请求体。 - 异常处理:需捕获
IOException
,并处理网络超时、连接失败等异常场景(可通过connection.setConnectTimeout()
和connection.setReadTimeout()
设置超时时间)。
使用Apache HttpClient发送JSON
Apache HttpClient是功能强大的HTTP客户端库,支持连接池、重试机制、异步请求等高级特性,适合复杂或高并发的场景,需先添加依赖(Maven):
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
示例代码:POST请求发送JSON
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; public class HttpClientJsonSender { public static void main(String[] args) { String targetUrl = "https://example.com/api/resource"; String jsonInput = "{\"name\":\"李四\",\"age\":25,\"city\":\"上海\"}"; // 1. 创建HttpClient对象 try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 2. 创建HttpPost请求 HttpPost httpPost = new HttpPost(targetUrl); httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); // 3. 设置请求体(JSON字符串) StringEntity entity = new StringEntity(jsonInput, "UTF-8"); httpPost.setEntity(entity); // 4. 执行请求,获取响应 try (CloseableHttpResponse response = httpClient.execute(httpPost)) { // 5. 处理响应 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("响应码: " + response.getStatusLine().getStatusCode()); System.out.println("响应内容: " + responseString); } EntityUtils.consume(responseEntity); // 确保实体内容被完全消费,释放连接 } } catch (Exception e) { e.printStackTrace(); } } }
关键点说明
- 连接池:通过
HttpClients.custom().setConnectionManager()
配置连接池,提升高并发性能。 - 实体处理:
StringEntity
直接封装JSON字符串,EntityUtils.toString()
将响应体转为字符串,必须调用EntityUtils.consume()
释放资源,避免连接泄漏。 - 异常处理:需处理
ClientProtocolException
(HTTP协议错误)和IOException
(网络错误)。
使用OkHttp发送JSON
OkHttp是Square公司开源的HTTP客户端,以简洁的API、高效的连接复用和异步支持著称,是Android开发和Java HTTP请求的热门选择,需添加依赖(Maven):
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency>
示例代码:POST请求发送JSON
import okhttp3.*; import java.io.IOException; public class OkHttpJsonSender { public static void main(String[] args) { String targetUrl = "https://example.com/api/resource"; String jsonInput = "{\"name\":\"王五\",\"age\":28,\"city\":\"广州\"}"; // 1. 创建OkHttpClient对象(可配置超时、拦截器等) OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS) .readTimeout(10, java.util.concurrent.TimeUnit.SECONDS) .build(); // 2. 创建请求体(JSON) MediaType JSON = MediaType.get("application/json; charset=utf-8"); RequestBody body = RequestBody.create(jsonInput, JSON); // 3. 创建请求 Request request = new Request.Builder() .url(targetUrl) .post(body) .header("Accept", "application/json") .build(); // 4. 发送请求(同步) try (Response response = okHttpClient.newCall(request).execute()) { if (response.isSuccessful()) { String responseString = response.body().string(); System.out.println("响应码: " + response.code()); System.out.println("响应内容: " + responseString); } else { System.out.println("请求失败,响应码: " + response.code()); } } catch (IOException e) { e.printStackTrace(); } } }
异步请求示例
// 异步发送请求(无需阻塞主线程) okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("请求失败: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseString = response.body().string(); System.out.println("响应内容: " + responseString); } else { System.out.println("请求失败,响应码: " + response.code()); } } });
关键点说明
- MediaType:通过
MediaType.get("application/json")
声明请求体类型,支持字符集设置。 - 同步/异步:
execute()
是同步调用,会阻塞当前线程;enqueue()
是异步调用,通过回调处理结果。 - 资源释放:响应体的
body().string()
只能调用一次,多次调用会抛出异常;同步模式下可通过try-with-resources
自动关闭Response
。
使用Spring Boot发送JSON
Spring Boot通过RestTemplate
(传统)或WebClient
(响应式,推荐)简化HTTP请求,是Spring生态中发送JSON的首选方式,需先添加依赖(Maven):
<!-- RestTemplate依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- WebClient依赖(响应式,需spring-boot-starter-webflux) --> <dependency> <groupId>org.springframework.boot</
还没有评论,来说两句吧...