Setting content type/ encoding in Jersey REST Client

Jalpa picture Jalpa · Jul 9, 2013 · Viewed 32k times · Source

HI I have been trying to call REST POST API using jersey REST Client. The API is docs is URL: METHOD: POST Header Info:- X-GWS-APP-NAME: XYZ Accept: application/json or application/xml

My Sample Jersey client code is

Client client = Client.create();

WebResource resource=client.resource(URL);

resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML);
resource.type(javax.ws.rs.core.MediaType.APPLICATION_XML);
resource.type("charset=utf-8");
ClientResponse response = resource.post(ClientResponse.class,myReqObj);

I have been trying this code variation since last 1 week and it is not working. Any help in this regard is highly appreciated.

Answer

TheArchitect picture TheArchitect · Jul 10, 2013

The tricky part is that the WebResource methods follows the Builder design pattern so it returns a Builder object which you need to preserve and carry on as you call further methods to set the full context of the request.

When you do resource.accept, it returns something you don't store, so it's lost when you do resource.type and therefore only your last call takes effect.

You'd typically set all the criterias in one line, but you could also save the output in a local variable.

ClientResponse response = client.resource(URL)
                                .accept(MediaType.APPLICATION_XML)
                                .type(MediaType.APPLICATION_XML)
                                .post(ClientResponse.class,myReqObj);