2012-01-26 263 views
1

我有一个服务器和一个客户端。我使用Spring来映射服务器和RestTemplate上的http请求,向服务器发出请求。RestTemplate POST请求RequestParams和RequestBody

服务器的代码如下所示:

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

这工作,因为正确的动作被触发,在服务器端从参数1 然而,请求的主体还包含:
param1 = val1
请求主体,当它被设置它将JSON所以我想要的是能够设置其他参数而不设置T他身体。 我知道我正在使用restTemplate不正确,所以任何帮助将不胜感激。

回答

1

您正在做HTTP POST,但是您没有提供一个对象来放POST ed。 Spring的RestTemplate试图找出你想要的东西POST,所以它看起来并且看到url的查询字符串有一些东西,所以它试图使用它。

不要将查询字符串添加到POST,只需提供您想要的对象POST

String postUrl = "http://myhost:8080/someEndPoint" 
restTemplate.postForLocation(postUrl, new ParamModel("val1")); 

本书Spring in Action (3rd edition)涵盖RestTemplate(和REST一般)相当不错。我会建议看看它。