2013-01-04 109 views
2

如何使用Spring RestTemplate發送數組參數?如何使用Spring RestTemplate發送數組?

這是在服務器端執行:

@RequestMapping(value = "/train", method = RequestMethod.GET) 
@ResponseBody 
public TrainResponse train(Locale locale, Model model, HttpServletRequest request, 
    @RequestParam String category, 
    @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId, 
    @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) 
{ 
    ... 
} 

這是我已經試過:

Map<String, Object> map = new HashMap<String, Object>(); 
map.put("category", parameters.getName()); 
map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array 
map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array 
TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map); 

以下是這顯然是不正確的實際要求網址:

http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657` 

一直在嘗試搜索,但無法找到解決方案。任何指針將不勝感激。

回答

9

Spring的UriComponentsBuilder可以做到這一點,也可以用於變量擴展。假設你想傳遞的字符串作爲參數「ATTR」對資源的數組,你只需要一個URI與路徑變量:

UriComponents comp = UriComponentsBuilder.fromHttpUrl(
    "http:/www.example.com/widgets/{widgetId}").queryParam("attr", "width", 
     "height").build(); 
UriComponents expanded = comp.expand(12); 
assertEquals("http:/www.example.com/widgets/12?attr=width&attr=height", 
    expanded.toString()); 

否則,如果您需要定義應該是一個URI在運行時擴展,並且您事先不知道數組大小,請使用帶有{?key *}佔位符的http://tools.ietf.org/html/rfc6570 UriTemplate,並使用https://github.com/damnhandy/Handy-URI-Templates的UriTemplate類進行擴展。

UriTemplate template = UriTemplate.fromTemplate(
    "http://example.com/widgets/{widgetId}{?attr*}"); 
template.set("attr", Arrays.asList(1, 2, 3)); 
String expanded = template.expand(); 
assertEquals("http://example.com/widgets/?attr=1&attr=2&attr=3", 
    expanded); 

對於Java以外的語言,請參見https://code.google.com/p/uri-templates/wiki/Implementations

0

試試這個

變化從

@RequestMapping(value = "/train", method = RequestMethod.GET) 

您的請求映射

@RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET) 

和restTemplate

您的網址

變更網址如下格式

http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9 
1

我結束了通過循環收集構建URL。

Map<String, Object> map = new HashMap<String, Object>(); 
map.put("category", parameters.getName()); 

String url = "http://localhost:8080/admin/train?category={category}"; 
if (positiveDocs != null && positiveDocs.size() > 0) { 
    for (String id : positiveDocs) { 
     url += "&positiveDocId[]=" + id; 
    } 
} 
if (negativeDocId != null && negativeDocId.size() > 0) { 
    for (String id : negativeDocId) { 
     url += "&negativeDocId[]=" + id; 
    } 
} 

TrainResponse response = restTemplate.getForObject(url, TrainResponse.class, map); 
相關問題