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();
Pair<String, String> keyValue = new ImmutablePair("key", "value");
put("email", "[email protected]"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate. postForEntity( url, params, String. class );
Using postForEntity()Find the postForEntity method declaration from Spring doc. url: The URL to post the request. request: The object to be posted. responseType: The type of response body.
The exchange method executes the request of any HTTP method and returns ResponseEntity instance. The exchange method can be used for HTTP DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE methods. Using exchange method we can perform CRUD operation i.e. create, read, update and delete data.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With