我必须在发布请求的正文中传递键值对。但是当我运行我的代码时,我收到错误消息“无法写入请求:没有为请求类型 [org.springframework.util.LinkedMultiValueMap] 和内容类型 [text/plain] 找到合适的 HttpMessageConverter”
我的代码如下:
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();
最佳答案
FormHttpMessageConverter
用于转换MultiValueMap
对象以便在HTTP 请求中发送。此转换器的默认媒体类型是 application/x-www-form-urlencoded
和 multipart/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);
关于java - 如何在java中使用resttemplate传递键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15269822/