How to pass key value pair using resttemplate in java
java, resttemplate
Solution
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);
Problem
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(); ```