Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call java Rest WebService inside a Servlet

I have a java Rest WebService URL http://localhost:8080/WebServiceEx/rest/hello/dgdg

When i execute the URL ,the WebService Method Returns a String

My Requirement is to call the above WebService URL inside a Servlet ,Could any one Help?

ServletCode:

public Class StoreServlet extends HttpServlet{
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

//Invoke WebService and Get Response String Here


} 

WebService Code:

public class HelloWorldService {
    @Context 
    private ServletContext context;

    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {

                    return Response.status(200).entity(msg).build();    

                }
    }
like image 466
IceCream Sandwitch Avatar asked Jun 25 '13 12:06

IceCream Sandwitch


People also ask

Can we create REST API using servlet?

In a similar way, you can create REST applications using only the Servlet API. However, there are other APIs that are designed to create REST applications.

How do you consume a REST webservice in Java?

Just make an http request to the required URL with correct query string, or request body. For example you could use java. net. HttpURLConnection and then consume via connection.

What servlet is called when a REST API request is made?

An HttpServlet is a natural, convenient way to implement RESTful web services for two main reasons.


1 Answers

Take a look at Apache CXF JAX-RS client:

http://cxf.apache.org/docs/jax-rs-client-api.html

e.g.

BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getBook();

Or, if you use JAX-RS 2.0, it has a client API

e.g.

Client client = ClientFactory.newClient();

String bal = client.target("http://.../atm/balance")
                   .queryParam("card", "111122223333")
                   .queryParam("pin", "9876")
                   .request("text/plain").get(String.class); 

Or you can do it the "core" way using just plain Java: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/

like image 148
Eran Medan Avatar answered Oct 20 '22 01:10

Eran Medan