簡體   English   中英

帶有參數的REST API查詢

[英]REST API Query with a parameter

我正在嘗試查詢看起來像這樣的服務器:

服務器代碼

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

當我用PostMan測試時,此方法有效

客戶代碼

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 我的代碼肯定存在其他問題。 我肯定是發送一個不是-1userId

您的queryUser()方法已映射到GET; 從客戶端,您調用POST restTemplate.postForEntity

我能夠通過使用UriComponentsBuilder來解決它。

UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(URI)
        .queryParam("userId", id);

從本質上講,它是將參數附加到URI,這是我認為PostMan所做的事情(這就是我的想法)。

參考: https : //www.oodlestechnologies.com/blogs/Learn-To-Make-REST-calls-With-RestTemplate-In-Spring-Boot

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM