Hitesh Rawal
Hitesh Rawal

Reputation: 25

RESTful API Client

I am new to RESTful API client development. I have a got the sample client code to integrate to REST Server. Below is the the snap shoot of same.

public TsbPublishClient() {
    client = javax.ws.rs.client.ClientBuilder.newClient();
    webTarget = client.target(BASE_URI).path("publication");
}
public <T> T getJson(Class<T> responseType, String product, String version, String category) throws ClientErrorException {
    WebTarget resource = webTarget;
    resource = resource.path(java.text.MessageFormat.format("registry/{0}/{1}/{2}", new Object[]{product, version, category}));
    return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}

public void close() {
    client.close();
}

My question is how do i invoke the getJson() method from my main class. The return type is T and it accepts responseType parameter which is of type Class <T>

Thanks in Advance.

Upvotes: 1

Views: 397

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

I'm a bit surprised that you want to use JAX-WS to access a RESTful API. In this technology, a web service operation invocation is represented by an XML-based protocol such as SOAP.

There are several technologies to do a call to a RESTful applications. Here are two of them:

  • Restlet - a lightweight and robust Java REST framework that tackles both client and server sides.
  • JAX-RS (JSR 311: JAX-RS: The Java API for RESTful Web Services) - a standardized API to both consume and produce RESTful applications. Restlet provides an implementation of this specification.

Following code describes a sample of client with Restlet:

ClientResource cr = new ClientResource("http://(...)/contacts");
MyDataBean bean = cr.get(MediaType.APPLICATION_JSON);

Following code describes a sample of client with JAX-RS:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://(...)")
                         .path("contacts");

MyDataBean bean = target
       .request(MediaType.APPLICATION_JSON_TYPE)
       .get(MyDataBean.class);

Both tools can leverage content (JSON, XML, YAML, ...) / POJO conversion with for example Jackson.

Hope it helps you, Thierry

Upvotes: 1

Related Questions