27

I've to pass key value pair in the body of post request. But when I run my code, I get the error as "Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [text/plain]"

My code is as follows:

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();
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Abhinandan Sharma
  • 273
  • 1
  • 3
  • 5

1 Answers1

36

The FormHttpMessageConverter is used to convert MultiValueMap objects for sending in HTTP requests. The default media types for this converter are application/x-www-form-urlencoded and multipart/form-data. By specifying the content-type as text/plain, you are telling RestTemplate to use the StringHttpMessageConverter

headers.setContentType(MediaType.TEXT_PLAIN); 

But that converter doesn't support converting a MultiValueMap, which is why you are getting the error. You have a couple of options. You can change the content-type to application/x-www-form-urlencoded

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

Or you can NOT set the content-type and let RestTemplate handle it for you. It will determine this based on the object you are attempting to convert. Try using the following request as an alternative.

ResponseEntity<String> model = restTemplate.postForEntity(giftango_us_url, bodyMap, String.class);
Roy Clarkson
  • 2,159
  • 18
  • 14
  • 3
    And ensure that the resttemplate is configured with a FormHttpMessageConverter if you're going to use the APPLICATION_FORM_URLENCODED too- – chrismarx Nov 24 '15 at 16:02