Spring RestTemplate post response

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

I'm not familiar with Spring RestTemplate.

But for this project I have to use Spring RestTemplate to send a POST call to consume a rest api.

I'm using this code:

String restCall = restTemplate.postForObject(url+restParm, null, String.class); 

This is working fine.

I would like to retriveve the HTTP status code (E.g: 200 OK.). How could I do that ? Thanks.

回答1:

You use the postForEntity method as follows...

ResponseEntity<String> response = restTemplate.postForEntity(url+restParm, null, String.class); HttpStatus status = response.getStatusCode(); String restCall = response.getBody(); 


回答2:

It will be pretty weird if RestTemplate couldn't get the response,as others have suggested. It is simply not true.

You just use the postForEntity method which returns a

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html

And as the documentation suggests, the response entity has the status.



回答3:

I would like to share my experience of using Spring RestTemplate. It really took me
a lot of time to fix it. My requirement: 1) Send POST to serverURI with parameters set in the HTTP body. The parameters should be wrapped as form data. 2). Get response with JSON data in the response body and customized Class name is passed to restTemplate. Result: Alwasy got NULL body in the response.

I searched on the website and tired every suggestions. body is still empty. So I tried to tell spring just return String to me instead of myCustomized Class. I saw the JSON string is returned. SO the reason why response body is null is because Spring cannot parse JSON to my customized class.

Finally, i fixed the NULL body issue by adding @JsonProperty annotation in my customized class definition. (I used @SerializedName in my Customized Class before and Spring cannot parse JSON to my object)



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