views:

257

answers:

3

Hi, 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

+2  A: 

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.

Vineet
+1  A: 

You don't mention what kind of service you want to invoke, but either way, your servlet is functioning as a service client, so you should be looking at service client technologies.

For invoking REST style services, java.net.URL or Apache Commons HttpClient can be used to send a request for a URL and fetch the reponse.

For invoking SOAP services, you can use Apache Axis, or Java WSIT.

mdma
+2  A: 

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.

ring bearer