Java Spring RestTemplate 发布响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16401909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:43:20  来源:igfitidea点击:

Spring RestTemplate post response

javaspringresttemplate

提问by Zamboo

I'm not familiar with Spring RestTemplate.

我不熟悉 Spring RestTemplate。

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

但是对于这个项目,我必须使用 Spring RestTemplate 发送 POST 调用来使用 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.

我想检索 HTTP 状态代码(例如:200 OK。)。我怎么能那样做?谢谢。

采纳答案by hyness

You use the postForEntity method as follows...

您使用 postForEntity 方法如下...

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

回答by Nikola Yovchev

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

如果 RestTemplate 不能像其他人建议的那样得到响应,那将是非常奇怪的。这根本不是真的。

You just use the postForEntitymethod which returns a

您只需使用postForEntity返回一个的方法

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

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.

正如文档所暗示的那样,响应实体具有状态。