Probbee
Probbee

Reputation: 1

Sending text REST message in Java w/ Spring

I have written a REST Request mapper:

@RequestMapping(value = "/resttest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> receiveBody(@RequestBody String bodymsg,HttpServletRequest request)  {
    String header_value = request.getHeader("h_key");       
    return new ResponseEntity<String>(HttpStatus.OK);
}

I would like to send a POST method to this like that:

public static void sendpost() {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("h_key","this is the value you need");
    HttpEntity<String> entity = new HttpEntity<String>("text body", headers);
    ResponseEntity<JSONObject> response = restTemplate
            .exchange("http://localhost:9800/resttest", HttpMethod.POST, entity,JSONObject.class);
}

But I get this error:

Unsupported Media Type

What is the problem with my sending method?

Upvotes: 0

Views: 1600

Answers (1)

wonhee
wonhee

Reputation: 1661

You set server side to accept plan text only, but your request sets content_type to "application/json"... means you are telling server side that you are sending JSON format, so that server side says "I don't support this media type" ( http error code 415 )

For what you said

I tried with REST GUI client sending data to controller and worked fine.

if you specify "content-type" in the REST GUI as "text/plain", probably you will get an same error code.

For

If I change the Controller consumes part to: ALL_VALUE it works fine.

, that's because now you are telling to server side code to take all the media type (Content-Type), so whatever value you set up in client side request, it doesn't matter anymore.

Upvotes: 2

Related Questions