如何在java中使用resttemplate传递键值对

时间:2013-03-07 11:20:48

标签: java resttemplate

我要在帖子请求的正文中传递键值对。但是当我运行我的代码时,我得到的错误为&#34;无法写入请求:找不到合适的HttpMessageConverter请求类型[org.springframework.util.LinkedMultiValueMap]和内容类型[text / plain]&#34; < / p>

我的代码如下:

MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>();
bodyMap.add(GiftangoRewardProviderConstants.GIFTANGO_SOLUTION_ID, giftango_solution_id);
bodyMap.add(GiftangoRewardProviderConstants.SECURITY_TOKEN, security_token);
bodyMap.add(GiftangoRewardProviderConstants.REQUEST_TYPE, request_type);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(bodyMap, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> model = restTemplate.exchange(giftango_us_url, HttpMethod.POST, request, String.class);
String response = model.getBody();

1 个答案:

答案 0 :(得分:28)

FormHttpMessageConverter用于转换MultiValueMap个对象以便在HTTP请求中发送。此转换器的默认媒体类型为application/x-www-form-urlencodedmultipart/form-data。通过将内容类型指定为text/plain,您告诉RestTemplate使用StringHttpMessageConverter

headers.setContentType(MediaType.TEXT_PLAIN); 

但该转换器不支持转换MultiValueMap,这就是您收到错误的原因。你有几个选择。您可以将内容类型更改为application/x-www-form-urlencoded

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

或者你不能设置内容类型并让RestTemplate为你处理它。它将根据您尝试转换的对象来确定这一点。尝试使用以下请求作为替代方案。

ResponseEntity<String> model = restTemplate.postForEntity(giftango_us_url, bodyMap, String.class);
相关问题