本文介绍了如何使用 Java 代码向 spring Boot 服务器发送 POST 请求。通过示例代码,展示了使用 java.net.httpURLConnection 和 java.net.http.HttpClient 两种方式实现 POST 请求,并强调了 Content-Type 设置的重要性。同时,对比两种方式的优缺点,帮助开发者选择更合适的方案。
向 spring boot 服务器发送 POST 请求是常见的任务,例如客户端提交数据到服务器进行处理。 本文将介绍两种在 Java 中发送 POST 请求的方法,并提供详细的代码示例和注意事项。
方法一:使用 java.net.HttpURLConnection
HttpURLConnection 是 Java 标准库提供的类,用于发送 HTTP 请求。 以下是使用 HttpURLConnection 发送 POST 请求的示例代码:
import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpURLConnectionExample { public static void main(String[] args) throws IOException { String url = "http://127.0.0.1:8090/online"; String query = "Body"; // 要发送的数据 HttpURLConnection urlConn; URL mUrl = new URL(url); urlConn = (HttpURLConnection) mUrl.openConnection(); // 设置请求方法为 POST urlConn.setRequestMethod("POST"); // 设置 Content-Type urlConn.setRequestProperty("Content-Type", "application/json"); // 根据实际情况修改 Content-Type // 允许输出 urlConn.setDoOutput(true); // 设置 Content-Length urlConn.setRequestProperty("Content-Length", integer.toString(query.length())); // 发送数据 urlConn.getOutputStream().write(query.getBytes(StandardCharsets.UTF_8)); // 获取响应状态码 int responseCode = urlConn.getResponseCode(); System.out.println("Response Code : " + responseCode); // 获取响应内容 (可选) // 可以使用 urlConn.getInputStream() 读取响应内容 } }
代码解释:
立即学习“Java免费学习笔记(深入)”;
- 创建 URL 对象: URL mUrl = new URL(url); 创建一个 URL 对象,指定请求的 URL 地址。
- 打开连接: urlConn = (HttpURLConnection) mUrl.openConnection(); 打开与 URL 的连接,并将其转换为 HttpURLConnection 对象。
- 设置请求方法: urlConn.setRequestMethod(“POST”); 设置请求方法为 POST。
- 设置 Content-Type: urlConn.setRequestProperty(“Content-Type”, “application/json”); 设置 Content-Type 头部。 这非常重要,服务器需要根据 Content-Type 知道如何解析请求体中的数据。 常见的 Content-Type 包括 application/json、application/x-www-form-urlencoded 和 text/plain。 请根据实际情况选择合适的 Content-Type。
- 允许输出: urlConn.setDoOutput(true); 允许向服务器发送数据。
- 设置 Content-Length: urlConn.setRequestProperty(“Content-Length”, Integer.toString(query.length())); 设置 Content-Length 头部,告诉服务器请求体的长度。 虽然不是必须的,但建议设置,可以提高效率。
- 发送数据: urlConn.getOutputStream().write(query.getBytes(StandardCharsets.UTF_8)); 将要发送的数据写入输出流。
- 获取响应状态码: int responseCode = urlConn.getResponseCode(); 获取服务器返回的 HTTP 状态码。 常用的状态码包括 200 (OK)、400 (Bad Request)、404 (Not Found) 和 500 (internal Server Error)。
- 获取响应内容 (可选): 可以使用 urlConn.getInputStream() 读取服务器返回的响应内容。
注意事项:
- 确保 Spring Boot 服务器正在运行,并且监听了指定的端口 (例如 8090)。
- Spring Boot 控制器需要正确处理 POST 请求,并且映射到相应的 URL (/online)。
- Content-Type 必须与 Spring Boot 控制器期望的类型一致。
方法二:使用 java.net.http.HttpClient (Java 11+)
HttpClient 是 Java 11 引入的新 HTTP 客户端 API,提供了更现代和易用的接口。 以下是使用 HttpClient 发送 POST 请求的示例代码:
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class HttpClientExample { public static void main(String[] args) throws IOException, InterruptedException { String url = "http://127.0.0.1:8090/online"; String query = "Body"; // 要发送的数据 HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Content-Type", "application/json") // 根据实际情况修改 Content-Type .POST(HttpRequest.BodyPublishers.ofString(query)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } }
代码解释:
立即学习“Java免费学习笔记(深入)”;
- 创建 HttpClient 对象: HttpClient client = HttpClient.newHttpClient(); 创建一个 HttpClient 对象。
- 创建 HttpRequest 对象: HttpRequest request = HttpRequest.newBuilder()…build(); 使用 HttpRequest.newBuilder() 创建一个 HttpRequest 对象,并设置请求的 URL、头部和请求体。
- 设置 URI: .uri(URI.create(url)) 设置请求的 URI。
- 设置 Content-Type: .header(“Content-Type”, “application/json”) 设置 Content-Type 头部。
- 设置请求体: .POST(HttpRequest.BodyPublishers.ofString(query)) 设置请求体。 HttpRequest.BodyPublishers 提供了一系列静态方法,用于创建不同类型的请求体,例如字符串、文件和字节数组。
- 发送请求: HttpResponse
response = client.send(request, HttpResponse.BodyHandlers.ofString()); 使用 HttpClient.send() 方法发送请求,并获取响应。 HttpResponse.BodyHandlers 提供了一系列静态方法,用于处理不同类型的响应体,例如字符串、字节数组和输入流。 - 获取响应状态码和内容: response.statusCode() 获取响应状态码, response.body() 获取响应体。
优点:
- 更现代和易用的 API。
- 支持异步请求。
- 更好的性能。
缺点:
- 需要 Java 11 或更高版本。
Spring Boot 服务器端代码示例
以下是一个简单的 Spring Boot 控制器,用于接收 POST 请求:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MessageService { @PostMapping(path = "/online") public ResponseEntity<?> getResponse(@RequestBody String requestBody) { System.out.println("Post Recieved"); System.out.println("Request Body: " + requestBody); return new ResponseEntity<>("Received: " + requestBody, HttpStatus.OK); } }
代码解释:
立即学习“Java免费学习笔记(深入)”;
- @RestController 注解表示这是一个 REST 控制器。
- @PostMapping(path = “/online”) 注解表示该方法处理 /online 路径的 POST 请求。
- @RequestBody String requestBody 注解表示将请求体中的数据绑定到 requestBody 参数。
- ResponseEntity> 返回一个包含响应状态码和响应体的 ResponseEntity 对象。
总结:
本文介绍了两种在 Java 中发送 POST 请求到 Spring Boot 服务器的方法。 HttpURLConnection 是 Java 标准库提供的类,兼容性好,但 API 相对复杂。 HttpClient 是 Java 11 引入的新 API,提供了更现代和易用的接口,但需要 Java 11 或更高版本。 选择哪种方法取决于具体的需求和环境。 无论使用哪种方法,都需要确保 Content-Type 设置正确,并且 Spring Boot 控制器能够正确处理 POST 请求。