I am using jersey-client-1.9
. sample code:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
Client client = Client.create();
webResource = client.resource("http://localhost:8047/storage/hive.json");
String input = //rest request
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
String queryRespose = response.getEntity(String.class);
As this project has changed from com.sun.jersey.api.client
to org.glassfish.jersey.client
. How to achieve this in jersey-client-2.8
?
Edit:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8047/query.json");
String input =//rest request
Response response = target.request().post(Entity.json(input));
String queryRespose = response.readEntity(String.class);
This worked...:)
With Jersey 2.x, you can build the Client
with ClientBuilder
Client client = ClientBuilder.newClient();
In Jersey 2.x WebTarget
is analogous to Jersey 1.x WebResource
, and instead of calling client.resource()
to get the WebResource
, you call client.target()
to get the WebTarget
WebTarget target = client.target(url);
Then you need to call request()
on the WebTarget
to get an Invocation.Builder
, which will allow you to chain other calls
Invocation.Builder invocation = target.request();
To send an entity, we need to pass an Entity
to one of the Invocation.Builder
's request method. For instance
Response response = builder.post(Entity.json(input);
To read the response, use response.readEntity(String.class)
. So altogether, you can do
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().post(Entity.json(input));
String entity = response.readEntity(String.class);
See Also:
You may also need the following dependency for JSON/POJO support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
Then register the JacksonFeature
with the client. This is so input
(if you want to use a POJO instead of String) can be serialized to JSON
client.register(JacksonFeature.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With