Jersey 2.x does not contain WebResource and resource class. What can I use instead?

7k Views Asked by At

I am trying to create a web API using Jersey. I am trying to run a method similar to this:

WebResource r = c.resource("http://localhost:8080/Jersey/rest/contacts");

However Jersey 2.x does not have a WebResource or Resource class. So what class can I use instead in order to have the uri http://localhost:8080/Jersey/rest/contacts as a parameter? This will be ran in a ContactClient class

2

There are 2 best solutions below

0
Paul Samsotha On

Have a look at the Client API from the Jersey documentation. With Jersey 2.x you instead want to use WebTarget. For example

Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().get();

See the documentation I linked to for much more information and examples.

0
Prasenjit Mahato On

JAX-RS 2.0 Client API: JAX-RS 2.0 introduces a new client API so that you can make http requests to your remote RESTful web services.

It is a 'fluent' request building API with really 3 main classes:

  1. Client,
  2. WebTarget, and
  3. Response.

1. Making a simple client request

Jersey 1.x way:

Client client = Client.create();
  WebResource webResource = client.resource(restURL).path("myresource/{param}");
  String result = webResource.pathParam("param", "value").get(String.class);

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
 WebTarget target = client.target(restURL).path("myresource/{param}");
 String result = target.pathParam("param", "value").get(String.class);

2. Attaching entity to request

Jersey 1.x way:

Client client = Client.create();
 WebResource webResource = client.resource(restURL);
 ClientResponse response = webResource.post(ClientResponse.class, "payload");

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
 WebTarget target = client.target(restURL);
 Response response = target.request().post(Entity.text("payload"), Response.class);