Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Jersey Rest Client more optimal than HttpClient for calling a restful service?

I am need to call the a resful api that will return json response. I am thinking about using jersey client api but not sure if it is in any way better than just using HttpClient directly and then using GSON to convert the response to Java objects.

like image 571
Place Places Avatar asked Dec 03 '25 05:12

Place Places


1 Answers

Jersey client is far better than HttpClient from a coding efficiency standpoint. Consider:

// Jersey client
WebResource resource = Client.create().resource("http://foo.com")
resource.path("widgets").entity(someWidget).type(APPLICATION_JSON).post();
Wodget wodget = resource.path("widgets/wodget").accept(APPLICATION_XML).get(Wodget.class);

as opposed to:

// HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://foo.com/widgets");
HttpEntity someWidgetEntity = ... // something with GSON to marshal the 'someWidget'
httpPost.setEntity(someWidgetEntity);
HttpResponse response = httpclient.execute(httpPost);

HttpGet httpGet = new HttpGet("http://foo.com/widgets/wodget");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
    ... // something with GSON to read in the wodget
}

Add in the fact that the Jersey client can use HttpClient under the covers for its HTTP interaction, and you get the best of both worlds: a simplified interface plus the power of a widely-used and versatile HTTP client library.

Note: Above code is completely untested but roughly accurate in shape.

like image 129
Ryan Stewart Avatar answered Dec 04 '25 23:12

Ryan Stewart