使用Spring RestTemplate时,REST POST可以正常使用POSTMAN,但是异常

问题描述 投票:9回答:1

我正在编写一个Rest客户端来使用Spring RestTemplate发布JSON数据。在正文中使用POSTMAN和跟随JSON数据获得正确的响应 -

{
    "InCode":"test",
    "Name":"This is  test",
    "Email":"[email protected]",
    "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", "[email protected]");
        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);
        }

我得到例外 -

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":"[email protected]","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)

感谢任何帮助。

java spring rest resttemplate spring-rest
1个回答
2
投票

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

相反,您必须使用'application / json'设置标题'Content-Type'。

编辑:

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

© www.soinside.com 2019 - 2024. All rights reserved.