gpt4 book ai didi

java - REST POST 与 POSTMAN 一起正常工作,但使用 Spring RestTemplate 时出现异常

转载 作者:IT老高 更新时间:2023-10-28 13:47:28 41 4
gpt4 key购买 nike

我正在编写一个 Rest 客户端来使用 Spring RestTemplate 发布 JSON 数据。在正文中使用 POSTMAN 并遵循 JSON 数据可以正确获取响应-

{
"InCode":"test",
"Name":"This is test",
"Email":"test@gmail.com",
"Id":18,
}

但是,当尝试使用 Spring RestTemplate 访问 REST API 时,如下所示

ResponseEntity<String> response = restTemplate.exchange(baseUrl,
HttpMethod.POST, getHeaders(), String.class);

private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
request.put("Email", "test@gmail.com");
request.put("Id", "18");
request.put("Name", "This is test");
request.put("InCode", "test");

headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(request.toString(), headers);
}

我得到了异常(exception)-

11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - Writing [{"InCode":"test","Email":"test@gmail.com","Id":"18","Name":"This is test"}] using [org.springframework.http.converter.StringHttpMessageConverter@6a1aab78]
11:52:57.574 [main] DEBUG o.s.web.client.RestTemplate - POST request for "http://server-test/platform/v4/org" resulted in 500 (Internal Server Error); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)

感谢您的帮助。

最佳答案

您正在设置“接受” header ,它定义了您将接受哪种内容类型作为响应。

相反,您必须将 header “Content-Type”设置为“application/json”。

编辑:

在您的 java 代码中,id 是一个字符串,在 postman 中是一个数字。可能这会导致服务器失败?

关于java - REST POST 与 POSTMAN 一起正常工作,但使用 Spring RestTemplate 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339753/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com