Saturday 6 August 2016

Restful web service client

Restful web service client

Here you go with sample program.

1) Create a class named "WebClients"!

package com.vimal.sample;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;

public class WebClients {

private static WebClient client;
public static WebClients INSTANCE = new WebClients();
public WebClient create(String url) {
WebClient clientCreate = client;
WebClient client = null;
try {
if (clientCreate != null) {
client = WebClient.fromClient(clientCreate);
client.path(url);
if(client != null) {
HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
       conduit.getClient().setReceiveTimeout(100000000);
       conduit.getClient().setConnectionTimeout(100000000);
}
client.async();
client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
}
} catch (Exception e) {
System.out.println("Webclient create method : " + e.getMessage());
}
return client;
}


static {
WebClient wclient = null;
try {
wclient = WebClient.create(UrlUtil.URL, true);
HTTPConduit conduit = WebClient.getConfig(wclient).getHttpConduit();
       conduit.getClient().setReceiveTimeout(12000000);
       conduit.getClient().setConnectionTimeout(12000000);
wclient.async();
wclient.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
} catch (Exception e) {
System.out.println("Webclients " + e.getMessage());
} finally {
setClient(wclient);
}
}

public static WebClient getClient() {
return client;
}

public static void setClient(WebClient client) {
WebClients.client = client;
}

}

2) How to use

String url = "sample url";
WebClient client = WebClients.INSTANCE.create(url);
Vimal resp = new Vimal();
resp = client.post(req, Vimal.class);
if(client != null) {
client.close();
}


enjoy........................

4 comments:

  1. What is the use of @Multipart..in restful api

    ReplyDelete
    Replies
    1. Basically content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data. In Restful API also, By using annotation "@multipart" working based on the rule of all multipart MIME data streams.

      Delete
  2. At first sight, these codes seemed very complicated for me and I had to find out more about it on another sites. Now, everything is clear to me.

    ReplyDelete