gpt4 book ai didi

java - 如何使用 Spring RestTemplate 发送数组?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:37 25 4
gpt4 key购买 nike

我如何使用 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);

以下为实际请求URL,明显错误:

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

一直在尝试四处搜索,但找不到解决方案。任何指针将不胜感激。

最佳答案

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,并且您事先不知道数组的大小,请使用 https://www.rfc-editor.org/rfc/rfc6570带有 {?key*} 占位符的 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 .

关于java - 如何使用 Spring RestTemplate 发送数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14153036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com