A Simple Client for Webservice

Now I am gonna set up a client which will use the url  - http://localhost:8080/Test/resources/test/ABC & will receive the result String "Hello ABC".

For that, we will start with a standalone java project in Eclipse.



Step: 1


   a. Create a new Java Project in Eclipse.
   b. Create a class with public static void main.
   c. Write the following code in it.


ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
String output = service.path("resources/test/ABC").get(String.class);
System.out.println(output );



and set getBaseURI as - 

private static URI getBaseURI()
{
     return uriBuilder.fromUri("http://localhost:8080/Test").build();
}

Again, we need to make some change in server code this time, as it was returning Response object. Now, what we can do is simply change the return type to String & add this code in return statement.

return "Hello"+name;

    d. We are going to need jersey-client.jar version 1.8 & jersey-core.jar version 1.8 for that. Just mention that in maven if it is a maven project, else you can just add it in the classpath. But, makesure that the versions of the jars are same.

And... voila !!!
Run the code & get the output "HELLO ABC".
Remember, this is calling a simple webservice which returns a string and this is very unusual for a web service. They usually returns XMLs or JSONs. So, when the webservice is returning XML or JSON, this code will not work.

Wisdom is not a product of schooling but of the lifelong attempt to acquire it.”  ― Albert Einstein

No comments :

Post a Comment