rreichel
rreichel

Reputation: 823

Spring MVC Override Received Content Type

I'm working on a Spring MVC application and have a client that I have no control over. This client is POSTing JSON data but transmitting a application/x-www-form-urlencoded header. Spring naturally trusts this header and tries to receive the data but can't because its JSON. Has anyone had experience overriding the header that Spring receives or just specifying exactly what type of data is coming, regardless of the headers?

Upvotes: 2

Views: 2528

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31901

Why don't you write a separate controller to handle application/x-www-form-urlencoded requests. If the request is a valid JSON, then you can parse it and forward it to to appropriate service.

This way you can also handle a case in future where you get request of same type which is not a valid JSON.

@RequestMapping(value = "/handleURLEncoded", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody Object handleURLEncoded(HttpEntity<String> httpEntity) {
    String json = httpEntity.getBody();
    //now you have your request as a String
    //you can manipulate it in any way

    if(isJSONValid(json)) {
        JSONObject jsonObj = new JSONObject(json);
        //forward request or call service directly from here
        //...
    }

    //other cases where it's not a valid JSON
}

Note: isJSONValid() method copied from this answer

Upvotes: 0

shazin
shazin

Reputation: 21923

You can do two things;

  1. Change the client to send the Content-Type: application/json header
  2. Write a Servlet Filter or Spring Interceptor which is on top of the Spring Controller and checks for the header Content-Type. If it is not application/json then it changes it to application/json.

Upvotes: 1

Related Questions