Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting content type/ encoding in Jersey REST Client

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.

like image 349
Jalpa Avatar asked Jul 09 '13 06:07

Jalpa


2 Answers

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);
like image 180
TheArchitect Avatar answered Sep 28 '22 09:09

TheArchitect


I do like that.

Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
    .accept(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(a, "application/json; charset=UTF-8"));

here, 'a' is account class instance which like

@XmlRootElement
public class account {
...
...
}
like image 42
nakai Avatar answered Sep 28 '22 09:09

nakai