Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call an external web service from a servlet

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

like image 603
pAkY88 Avatar asked May 17 '10 20:05

pAkY88


People also ask

How can we communicate from one servlet to another?

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.

Can we call servlet from JSP?

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".

What is HttpServletRequest and HttpServletResponse?

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.


2 Answers

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.

like image 64
ring bearer Avatar answered Oct 11 '22 21:10

ring bearer


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.

like image 26
Vineet Avatar answered Oct 11 '22 20:10

Vineet