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
The communication between the Java servlets is known as Servlet communication. It is sending users request, and the response object passed to a servlet to another servlet. We are using the method getParameter(), which is basically used to get the input from user value in a specified field.
Alternatively, you can pass data between a JSP page and a servlet through an appropriately scoped JavaBean or through attributes of the HTTP request object. Using attributes of the request object is discussed later, in "Passing Data Between a JSP Page and a Servlet".
The HttpServletRequest object can be used to retrieve incoming HTTP request headers and form data. The HttpServletResponse object can be used to set the HTTP response headers (e.g., content-type) and the response message body.
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.
To make any request to an outside service, you'll have to explicitly make a new HTTP request and handle its response. Take a look at the HttpUrlConnection class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With