restTemplate getForObject中map傳參問題


在使用restTemplate中getForObject的map傳參形式時:

開始時我是這么調用的:

RestTemplate rest = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("s", "hello");
String url = "http://localhost:8990/drce/hello";
String s = rest.getForObject(url , String.class,params);
System.out.println(s);

結果是服務端接收不到參數,報參數異常

 

 問題就出在第一次參數“url”這里了,這里的url需要攜帶參數,格式為url+?服務端參數名={map參數名}

改寫為一下寫法就可以正常運行了:

RestTemplate rest = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("s", "hello");
String url = "http://localhost:8990/drce/hello";
String s = rest.getForObject(url + "?s={s}", String.class,params);
System.out.println(s);

 

在看源碼后,了解到restTemplate會用一個工具類去解析前面的url,提取出host,port等信息,如果不加參數,他就認為你不需要傳參,所以map就不生效了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM