dsb*_*dsb 2 java spring controller resttemplate
我不知道如何将 Java 列表传递到 Spring RestTemplate 调用中,然后在 Controller 方法中使用该列表
客户端代码:
public String generateInfoOfIds(List<String> ids, String userName, String password){
RestTemplate restTemplate = new RestTemplate();
String response = null;
String url = "https://someservice.com/getInfoOfIds?";
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(userName, password));
response = restTemplate.exchange(url+"ids=" + ids, HttpMethod.GET, null, String.class);
return response;
}
Run Code Online (Sandbox Code Playgroud)
控制器代码:
@RequestMapping(value = "/getInfoOfIds", method = RequestMethod.GET)
public String getInfoOfIds(@RequestParam("ids") List<String> ids) {
String response = myService.doSomeWork(ids);
return response;
}
Run Code Online (Sandbox Code Playgroud)
对控制器本身的调用有效,但 List 未正确转换为 @RequestParam id。
在 Spring 中,如何将 List 从 RestTemplate 传递到 Controller?
response = restTemplate.exchange(url+"ids=" + ids, HttpMethod.GET, null, String.class);
Run Code Online (Sandbox Code Playgroud)
在您的客户端代码中,它应该是逗号分隔值(ids=1,2,3 )或多个连接值(ids=1&ids=2&ids=3),但您将整个对象作为第一个参数传递给restTemplate.exchange它将使用 toString() 方法进行转换,看起来像这样ids=[123, 321]并且它与预期的格式不同。
格式化字符串的解决方案
JDK >= 8
String idsAsParam = ids.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
response = restTemplate.exchange(url+"ids=" + idsAsParam, HttpMethod.GET, null, String.class);
Run Code Online (Sandbox Code Playgroud)
JDK<8
String idsAsParam = ids.toString()
.replace(", ", ",") //remove space after the commas
.replace("[", "") //remove the left bracket
.replace("]", "") //remove the right bracket
.trim(); //remove trailing spaces from partially initialized arrays
response = restTemplate.exchange(url + "ids=" + idsAsParam, HttpMethod.GET, null, String.class);
Run Code Online (Sandbox Code Playgroud)
使用 RestTemplate 的解决方案
您还可以使用 UriTemplate 的模式匹配功能来实现此目的。它与 Map 对象作为参数配合得很好。键应该与 URI 键匹配,值应该是一个数组,可以从列表创建。例子:
String url = "http://google.com";
List<String> params = Arrays.asList("111", "222", "333");
Map<String, Object> map = new HashMap<>();
map.put("ids[]", params.toArray());
restTemplate.exchange(url + "?ids={ids[]}", HttpMethod.GET, null, String.class, map);
Run Code Online (Sandbox Code Playgroud)
结果变成
"http://google.com?ids=111,222,333"
| 归档时间: |
|
| 查看次数: |
1974 次 |
| 最近记录: |