【问题标题】:How to pass key value pair using resttemplate in java如何在java中使用resttemplate传递键值对
【发布时间】:2013-03-07 11:20:47
【问题描述】:

我必须在发布请求的正文中传递键值对。但是当我运行我的代码时,我收到错误消息“无法写入请求:没有为请求类型 [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();

【问题讨论】:

    标签: java resttemplate


    【解决方案1】:

    FormHttpMessageConverter 用于转换 MultiValueMap 对象以在 HTTP 请求中发送。此转换器的默认媒体类型为application/x-www-form-urlencodedmultipart/form-data。通过将 content-type 指定为 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);
    

    【讨论】:

    • 如果你也打算使用 APPLICATION_FORM_URLENCODED,请确保 resttemplate 配置了 FormHttpMessageConverter-
    猜你喜欢
    • 2023-03-21
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2018-02-02
    • 2011-09-10
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多