Adam Bien's Weblog

Simplest Possible REST Client

To access the Simplest Possible REST Endpoint from Java, you will have to implement some code:


import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

  final String URI = "http://localhost:8080/hello-rest/resources/message";
		//...
        Client client = ClientBuilder.newClient();
        String result = client.target(URI).
                request().
                get(String.class);
        assertThat(result, containsString("duke"));

For server-to-server communication no additional dependency is required. If you are using the client as test driver, you will have to declare the dependency to the SPI of you choice e.g.


<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.21</version>
</dependency>

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Or

String result = Unirest.get("http://localhost:8080/hello-rest/resources/message"). asString();

<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>

Posted by Urb on May 11, 2016 at 11:29 AM CEST #

Unirest's API is nice, but not much better:

String result = Unirest.get("http://localhost:8080/hello-rest/resources/message"). asString();

VS

String result = ClientBuilder.newClient().target("http://localhost:8080/hello-rest/resources/message").request().get(String.class);

I like to rely on Java EE dependencies whenever possible when deploying to an application server. Unirest and its transitive dependencies add about 2MB to the WAR. Whether or not that 2MB is justified depends on the project, but as Adam Bien has pointed out (http://www.adam-bien.com/roller/abien/entry/ears_wars_and_size_matters), the smaller the WAR, the faster the deploy.

Posted by David on May 11, 2016 at 06:46 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License