我试图在我的 Springboot 应用程序中使用 HTTPClient 将 JSON POST 请求发送到 URL,但我从服务器收到 400 状态响应。 但是,当我使用 Postman 发送相同的请求时,我从服务器收到了所需的响应。
这是我的代码:
// some dummy url:
String url = "http://88.22.199.111:5000/detect";
JSONObject json1 = new JSONObject();
json1.put("From", "Sawan");
json1.put("to", "Mohan");
json1.put("message", "is API working?");
json1.put("check_list", 1);
HttpClient httpClient = HttpClient.newBuilder().build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json1.toString()))
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(httpResponse.statusCode());
System.out.println(httpResponse.body());
这是控制台上的输出:
400 {“消息”:“浏览器(或代理)发送了该服务器无法理解的请求。”}
当我通过 Postman 使用以下详细信息点击相同的 URL 时,我从服务器得到了所需的响应:
请求类型:POST
网址:同上网址
正文(JSON):
{
"From":"sawan"
,"to":"mohan"
,"message":"is API working?"
,"check_list":1
}
期望的输出:
{
"status": 200,
"message": "Success",
"timestamp": "2023-03-31 05:20:33.455868 +0000",
"data": {
"Message": "is API working?",
"MessageTimeUTC": "Fri, 31 Mar 2023 05:20:33 GMT",
"Message_By": "sawan",
"Message_To": "mohan",
"Message_Intended_For": "mohan",
"Sentences": []
}
此外,当我使用 RestTemplate 类时,它工作正常,我在控制台上获得了所需的输出,但在实际应用程序中我不能使用 springboot 的 RestTemplate 类,所以我需要帮助。
我的代码有什么问题吗?我是否需要在我的请求中包含任何额外的标头?任何帮助将不胜感激。