Below is the web service for which I am going to write a client. You have to start this service first. (You can get a quick knowledge about Jersey RESTful web services by looking at this tutorial)
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class HelloService {
@GET
@Path("/{company}")
@Produces("text/plain")
public Response getWelcomeMessage(@PathParam("company") String company,
@QueryParam("username") String username) {
String retVal = "Welcome to " + company + " " + username + ".!";
return Response.status(200).entity(retVal).build();
}
}
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class HelloService {
@GET
@Path("/{company}")
@Produces("text/plain")
public Response getWelcomeMessage(@PathParam("company") String company,
@QueryParam("username") String username) {
String retVal = "Welcome to " + company + " " + username + ".!";
return Response.status(200).entity(retVal).build();
}
}
This is the client which can consume above service.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class MyClient {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource =
client.resource("http://localhost:8090/MifeRest/hello");
ClientResponse response = webResource.path("ABC org") //setting path param
.queryParam("username", "John") //setting query param
.accept("text/plain") //setting accept MIME type
.get(ClientResponse.class); //send GET request
if (response.getStatus() != 200) {
System.out.println("Error : " + response.getStatus());
}
String responseText = response.getEntity(String.class);
System.out.println(responseText); //response body
System.out.println(response.getHeaders().get("content-type")); //header value
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class MyClient {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource =
client.resource("http://localhost:8090/MifeRest/hello");
ClientResponse response = webResource.path("ABC org") //setting path param
.queryParam("username", "John") //setting query param
.accept("text/plain") //setting accept MIME type
.get(ClientResponse.class); //send GET request
if (response.getStatus() != 200) {
System.out.println("Error : " + response.getStatus());
}
String responseText = response.getEntity(String.class);
System.out.println(responseText); //response body
System.out.println(response.getHeaders().get("content-type")); //header value
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment