REST POST works correctly with POSTMAN but exception when using Spring RestTemplate

人走茶凉 提交于 2019-12-05 19:13:08

问题


I am writing a Rest client to post JSON data using Spring RestTemplate. Using POSTMAN and following JSON data in body get the response correctly-

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

However when trying to hit the REST API using Spring RestTemplate as follows

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);
        }

I get the 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)

Would be thankful for any help.


回答1:


You are setting the 'Accept' header, which defines which content type you will accept as a response.

Instead you must set the header 'Content-Type' with 'application/json'.

Edit:

In your java code id is a string, in the postman its a number. May be this makes the server fail?



来源:https://stackoverflow.com/questions/37339753/rest-post-works-correctly-with-postman-but-exception-when-using-spring-resttempl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!