HttpMessageConverter exception : RestClientException: Could not write request: no suitable HttpMessageConverter found

WhiteBird :

I am writing a client to consume a RESTful service. I am required to send the request in key, value pair, they suggested that I use a Map for this. The RESTful service that I am calling is only going to accept JSON and my client is going to be in Java. It is actually going to be part of an existing enterprise EJB project.

I have written up a client and am able to call the RESTful service successfully. In fact, if I send the request in String (JSON format) then I even get a response back. But I would like to avoid this manual work of converting the Map into a JSON format string and then sending it out in Request.

I have set Content-Type as application/json and have created a Map which will contain the KeyValue pair.

Snippet of code from Client:

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(MyConstants.JWT_AUTH_TOK, restUtil.getJWTToken());

restTemplate = new RestTemplate();

ModelReqVO modVO = new ModelReqVO();
Map<String, String> dataMap = new HashMap<String, String>();
//Setting key,value into datamap (e.g. "key1", "value1")
modVO.setDataMap(dataMap);

ResponseEntity<ModelRspnsVO> result = restTemplate.postForEntity(mySrvcFN, new HttpEntity(modVO, headers), ModelRspnsVO.class);

Request (ModelReqVO) Class:

public class ModelReqVO {

private HashMap<String, String> dataMap;

ModelReqVO() {
    this.dataMap = new HashMap<String, String>();
}

//getter and setter generated
}

This is the exception that I am getting-

RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [com.mycomp.myproj.ModelReqVO] and content type [application/json].

I checked the HttpMessageConverters that I have on my restTemplate and I did find MappingJacksonHttpMessageConverter. Is something else required of me in the code to use the said converter?

I found a couple of examples on Spring.io forums, but they were about a service which required www/form content and not JSON. I, surprisingly, do not find any details about using a particular converter for Map to be sent as a JSON.

Note: The code snippets might have compile errors, I have typed the code out from my mobile. I cannot use the internet on the machine that I code in for security reasons.

Deadpool :

The error message says no suitable HttpMessageConverter found for request type, so just add MappingJackson2HttpMessageConverter with MediaType to RestTemplate

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 
coverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON); 
restTemplate.getMessageConverters().add(0, converter)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160222&siteId=1