我想查询,看起来像这样的服务器:
@RequestMapping(value = "/query_user", method = RequestMethod.GET)
public String queryUser(@RequestParam(value="userId", defaultValue="-1") String userId)
{
int id = Integer.parseInt(userId);
User user = this.service.getUser(id);
...
return userJson;
}
此方法适用,当我和邮递员测试
private synchronized void callServer(int id)
{
final String URI = "http://localhost:8081/query_user";
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap();
map.add("userId", id);
restTemplate.getMessageConverters()
.add(new MappingJackson2HttpMessageConverter());
// Modified to use getForEntity but still this is not working.
ResponseEntity<String> response
= restTemplate.getForEntity(URI, String.class, map);
}
我怎样才能解决这个问题?重要的是,我收到来自服务器端的userJson
。
切换到getForEntity()
方法后,我不断收到defaultValue
对服务器端的-1
。一定有别的东西错我的代码。我definitly发送userId
,是不是-1
。
你queryUser()
方法映射到GET;从客户端调用POST restTemplate.postForEntity
我可以通过使用UriComponentsBuilder
来解决它。
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(URI)
.queryParam("userId", id);
本质上,它是附加参数的URI是什么,我相信邮递员正在做(这就是我想过这个问题)。
参考:https://www.oodlestechnologies.com/blogs/Learn-To-Make-REST-calls-With-RestTemplate-In-Spring-Boot