mercredi 15 avril 2015

How to write controller class to allow content-type: application/json and application/x-www-form-urlencoded

I am sending request to my controller class request as content-Type: application/json and application/x-www-form-urlencoded format It should allow both types.


below is my controller class.



@RequestMapping(value = "/home", method = RequestMethod.POST)
public String getCustomer(@ModelAttribute HomeRequest homeRequestequest,
HttpServletRequest request) {

String response = homeService.getCustomerResponse(homeRequestequest, request);
return response;
}


In service class I written below code. Here I am calling another api



public String getCustomerResponse(@ModelAttribute HomeRequest homeRequest,
HttpServletRequest request) {
String url="https://somthing---";
HttpHeaders header = new HttpHeaders();
header.add("Api-Key", "RTM");
header.add("Accept", "application/json;v=3");
header.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new Gson();
messageRequest = gson.toJson(messageNotification);
HttpEntity<?> entityRequest = new HttpEntity<Object>(messageRequest, header);
Map<String, String> urlVariables = new HashMap<String, String>();
return restTemplate.exchange(url, HttpMethod.POST, entityRequest, String.class,
urlVariables);


But when I am using request type as a application/x-www-form-urlencoded it is working but when I use request application/json this code is not working it is giving 400 response status. How to solve this issue.


Aucun commentaire:

Enregistrer un commentaire