RestTemplate POST 请求 RequestParams 和 RequestBody
-
14-11-2019 - |
题
我有一个服务器和一个客户端。我使用 Spring 在服务器上映射 http 请求,并使用 RestTemplate 向服务器发出请求。
服务器代码如下所示:
@RequestMapping (value="/someEndPoint", method = RequestMethod.POST)
@ResponseBody
public String configureSettings(
@RequestParam(required=false) Integer param1,
@RequestParam(required=false) Long param2,
@RequestBody String body)
{
if(param1 != null)
// do something
if(body not empty or null)
//do something
}
客户端:
String postUrl = "http://myhost:8080/someEndPoint?param1=val1"
restTemplate.postForLocation(postUrl, null);
这起作用的是,正确的操作是从param1上触发在服务器端的,但是请求的主体还包含:
参数1=值1
设置请求正文时,它将是 json,所以我想要的只是能够在不设置正文的情况下设置其他参数。我知道我错误地使用了restTemplate,因此我们将不胜感激任何帮助。
解决方案
你正在做一个 HTTP POST
, ,但是您没有提供要放置的对象 POST
编辑。春天的 RestTemplate
正在试图弄清楚你想要什么 POST
, ,所以它看起来并发现 url 的查询字符串有一些东西,所以它尝试使用它。
不要将查询字符串添加到 POST
, ,只需提供您想要的对象 POST
.
String postUrl = "http://myhost:8080/someEndPoint"
restTemplate.postForLocation(postUrl, new ParamModel("val1"));
这本书 Spring in Action (3rd edition)
盖子 RestTemplate
(以及一般的 REST)很好。我建议看一下。
不隶属于 StackOverflow