I'm developing a servlet that gets a name of a web service and could be forward the request to an external web service, for example: http://www.webservice.com/...
I have build a response wrapper that intercept response output but I can't forward request to an external web service, it works only if I redirect the request to a servlet that is on same server.
Example:
request.getRequestDispatcher("aMyServlet").forward(request, response) // WORKS
request.getRequestDispatcher("http://www.webservice.com/...").forward(request, response)
Doesn't because Tomcat searches http://www.webservice.com/...
on the server as a local resource.
How can I do external request?
Thanks
forward
method that you are using is used for communicating between server resources, (eg: servlet to servlet as you have found out) If you want to redirect to another location, you can use the HttpServletResponse's sendRedirect
method.
Better option is to
Perform your own HTTP request and stream the results back to the
browser. This sounds harder than it is. Basically you create a
java.net.HttpURLConnection
with the URL of the web site you want to
"redirect" to. This can actually contain the query parameters (as long as
they're not too large) since it will never be sent to the user's browser
either and will not appear in the browser URL bar. Open the connection, get
the content and write it to the Servlet's OutputStream.