How to call java Rest WebService inside a servlet

I have a Java Java Web service URL for http://localhost:8080/WebServiceEx/rest/hello/dgdg

When I run the URL, the WebService method returns a string

My requirement is to call the aforementioned WebService url inside the servlet, can there be any 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(); } } 
+6
source share
2 answers

Take a look at the Apache CXF JAX-RS client:

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

eg.

 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 are using JAX-RS 2.0, it has a client API .

eg.

 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 in the β€œmain” way using simple Java: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/

+4
source

One of the possibilities is to create a webservice client using jaxws (for this purpose, search for a textbook on the Internet). This way you get some Java classes that you can use, as usual, inside your servlet.

0
source

Source: https://habr.com/ru/post/948057/


All Articles