REST API查询与参数

问题描述 投票:0回答:2

我想查询,看起来像这样的服务器:

服务器代码

@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

java spring-boot resttemplate
2个回答
1
投票

queryUser()方法映射到GET;从客户端调用POST restTemplate.postForEntity


0
投票

我可以通过使用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

© www.soinside.com 2019 - 2024. All rights reserved.