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

Abh*_*rma 26 java resttemplate

我要在post请求的主体中传递键值对.但是当我运行我的代码时,我得到错误为"无法写入请求:找不到合适的HttpMessageConverter请求类型[org.springframework.util.LinkedMultiValueMap]和内容类型[text/plain]"

我的代码如下:

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();
Run Code Online (Sandbox Code Playgroud)

Roy*_*son 31

FormHttpMessageConverter是用来转换MultiValueMap对象在HTTP请求发送.此转换器的默认媒体类型是application/x-www-form-urlencodedmultipart/form-data.通过将content-type指定为text/plain,您告诉RestTemplate使用StringHttpMessageConverter

headers.setContentType(MediaType.TEXT_PLAIN); 
Run Code Online (Sandbox Code Playgroud)

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

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
Run Code Online (Sandbox Code Playgroud)

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

ResponseEntity<String> model = restTemplate.postForEntity(giftango_us_url, bodyMap, String.class);
Run Code Online (Sandbox Code Playgroud)

  • 如果您也要使用APPLICATION_FORM_URLENCODED,请确保其余模板都使用FormHttpMessageConverter配置- (3认同)