Call an external web service from a servlet

I am developing a servlet that gets the name of a web service and can redirect a request to an external web service, for example: http://www.webservice.com/...

I am creating a response wrapper that intercepts the response, but I cannot redirect the request to an external web service, it only works if I redirect the request to a servlet located on the same server.

Example:

 request.getRequestDispatcher("aMyServlet").forward(request, response) // WORKS request.getRequestDispatcher("http://www.webservice.com/...").forward(request, response) 

Not because Tomcat is looking for http://www.webservice.com/... on the server as a local resource.

How can I execute an external request?

thanks

+6
java servlets forward
source share
3 answers

To make any request to an external service, you will have to explicitly create a new HTTP request and process its response. Take a look at the HttpUrlConnection class.

+2
source share
Method used

forward used to communicate between server resources (for example: servlet server, as you found out). If you want to redirect to another place, you can use the HttpServletResponse sendRedirect method. The best option is to make your own HTTP request and send the results back to the browser. It sounds more complicated than it is. You basically create java.net.HttpURLConnection with the URL of the website you want to redirect to. This may actually contain the request parameters (as long as they are not too large), since it will never be sent to the user's browser and will not be displayed in the browser URL bar. Open a connection, get the contents and write it to the Servlet OutputStream.

+4
source share

You do not specify which service you want to call, but in any case, your servlet acts as a service client, so you should look at the technology of client clients.

To call REST-style services, java.net.URL or Apache Commons HttpClient can be used to send a request to a URL and receive a response.

You can use Apache Axis or Java WSIT to invoke SOAP services.

+1
source share

All Articles