可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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)