SpringBoot客户端发送POST请求未被服务端接收的问题求助
问题分析与修复
你的客户端代码存在三个关键问题,导致SpringBoot服务端无法接收请求:
1. 未显式设置请求方法为POST
HttpURLConnection默认使用GET请求,而你的服务端接口仅接收POST请求,必须显式指定请求方法:
urlConn.setRequestMethod("POST");
2. Content-Type请求头设置错误
你设置的application/POST是无效的MIME类型,根据你的请求体是普通字符串,应改为text/plain(如果是JSON数据则用application/json,表单数据用application/x-www-form-urlencoded):
urlConn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
3. 未触发请求提交
仅向输出流写入数据不会自动发送请求,需要调用getResponseCode()或getInputStream()来完成请求提交,同时可通过响应状态码排查问题。
修改后的完整StartupService代码
public void init() throws IOException { String query = "Body"; Client client = new Client(); HttpURLConnection urlConn; URL mUrl = new URL(client.getUrl() + "/online"); urlConn = (HttpURLConnection) mUrl.openConnection(); // 设置请求方法为POST urlConn.setRequestMethod("POST"); // 设置正确的Content-Type urlConn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8"); urlConn.setDoOutput(true); // 写入请求体,用try-with-resources自动关闭流 try (OutputStream os = urlConn.getOutputStream()) { byte[] input = query.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } // 触发请求并打印响应状态 int responseCode = urlConn.getResponseCode(); System.out.println("Post Sent, Response Code: " + responseCode); }
额外提示
- 使用try-with-resources语法可避免资源泄漏
- 打印响应状态码和响应内容,能更直观地调试请求是否成功
内容的提问来源于stack exchange,提问作者Alex_X1
相关产品推荐
相关产品推荐

