如何在rest模板中发送带有HTTPEntity的List <t>

时间:2017-01-11 09:53:54

标签: resttemplate

线程中的异常&#34; main&#34;

  

org.springframework.web.client.HttpClientErrorException:400 Bad   请求

我的代码是

RestTemplate restTemplate = new RestTemplate();

UriComponentsBuilder builder  = UriComponentsBuilder.fromHttpUrl(Constants.ADD_EVENT_URL)
                    .queryParam("dataMap", eventsList);

String paramUrl = builder.build().encode().toString();

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<List<T>> httpEntity = new HttpEntity<List<T>>(eventsList, requestHeaders);

ResponseEntity<String> eventsAdded = restTemplate.exchange (paramUrl, HttpMethod.POST, httpEntity,String.class);

1 个答案:

答案 0 :(得分:0)

我意识到这有点旧,但我认为客户端设置为接收某种类型的集合?

HTTP 400会在您的请求格式错误时发生,因此您的实体不正确,或者您没有提供正确的路径参数,请求参数和/或实体信息。

从正在构造的URI看起来,您试图将列表作为查询字符串参数传递,并作为请求体的一部分,这是多余的。

也许尝试像

这样的东西
UriComponentsBuilder builder  = UriComponentsBuilder.fromUrlString(Constants.ADD_EVENT_URL);

...

HttpEntity<List<T>> httpEntity = new HttpEntity<List<T>>(eventsList, requestHeaders);

ResponseEntity<String> eventsAdded = restTemplate.exchange (builder.toUriString(), HttpMethod.POST, httpEntity, String.class);

OR

UriComponentsBuilder builder  = UriComponentsBuilder.fromHttpUrl(Constants.ADD_EVENT_URL)
                        .queryParam("dataMap", eventsList);

    ...

    ResponseEntity<String> eventsAdded = restTemplate.exchange (builder.toUriString(), HttpMethod.POST, null, String.class);