Setting content type/ encoding in Jersey REST Client
Asked Answered
D

2

6

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.

Diorite answered 9/7, 2013 at 6:15 Comment(0)
A
9

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);
Abject answered 9/7, 2013 at 23:12 Comment(0)
G
1

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 {
...
...
}
Go answered 19/12, 2015 at 16:19 Comment(1)
Is this for Jersey 2? It seems... unusual, maybe you could expand the answer a little?Rone

© 2022 - 2024 — McMap. All rights reserved.