2014-02-17 50 views
12

我想訪問一個API的內容,我需要使用RestTemplate發送一個URL。在Spring中使用RestTemplate。異常 - 沒有足夠的變量可用於擴展

String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={\"price\":\"desc\"}"; 

OutputPage page = restTemplate.getForObject(url1, OutputPage .class); 

但是,我收到以下錯誤。

Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '"price"' 
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:284) 
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:220) 
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:317) 
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:46) 
at org.springframework.web.util.UriComponents.expand(UriComponents.java:162) 
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:119) 
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:501) 
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239) 
at hello.Application.main(Application.java:26) 

如果我刪除排序條件,它工作正常。 我需要使用排序條件來解析JSON。 任何幫助將不勝感激。

感謝

回答

34

的根本原因是RestTemplate認爲花括號中給定的URL作爲URI變量的佔位符{...},並嘗試基於其名稱來替代它們。例如

{pageSize} 

會試圖獲得一個名爲pageSize的URI變量。這些URI變量是用一些其他重載的方法指定的。您尚未提供任何內容,但您的網址需要一個,因此該方法會引發異常。

一種解決方案是使String對象包含值

String sort = "{\"price\":\"desc\"}"; 

,並在您的網址

String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}"; 

提供一個真正的URI變量你會打電話給你getForObject()像這樣

OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort); 

我強烈建議你不要發送任何JSON請求GET請求的參數,而是將其發送到POST請求的主體中。

2

可以URL編碼參數值:

String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort="; 

org.apache.commons.codec.net.URLCodec codec = new org.apache.commons.codec.net.URLCodec(); 
url1 = url1 + codec.encode("{\"price\":\"desc\"}"); 
OutputPage page = restTemplate.getForObject(url1, OutputPage.class); 
相關問題