hi there ! is there an easy way to send a HTTP POST message from a servlet ? actually, if this helps, the servlet should sort of forward to another page but extend the request which was sent to the servlet by a few parameters. what's the trick ? thanks people dennis
Joined: Nov 22, 2008
I found a bit of code which does what I want, but with a GET: RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/some.ThirdPartyServlet" + "?" + "param_name=" + "somevalue"); dispatcher.forward(request, response); What I'm looking for is exactly this, but with POST !
to forward to another servlet or JSP page, you can use the forward method of the Request Dispatcher.
As for including additional parameters you could accomplish this with the setAttribute/getAttribute pair of methods on the request object. This would mean your 2nd and subsequent resources would need to be aware that relevant information is divided between the parameter and attribute 'spaces' (they'd need to use both getParameter and getAttriute in order to retrieve everything.)
An alternative you might want to investigate is the use of Filters. If your first servlet's only job is to examine the incoming request, add an attribute or two, and then forward it along, then Filters are a good substitute.
Hi dennis, I started to write my reply just before you posted your second post.
When you do this: ThirdPartyServlet" + "?" + "param_name=" + "somevalue");
You are *making* your request a GET.
If you POST to the first servlet and then just forward, the second servlet will receive it as a POST as well.
Joined: Nov 22, 2008
okay, but if I just want to send an HTTP request to a remote URL (I forgot to mention that it's a remote resource, sorry), like with using response.sendRedirect(), what's the solution ? sendRedirect() is great but I think I can't include any HTTP POST parameters, right ?
That is correct, you can't POST with a redirect. One possible solution would be to use HttpURLConnection to connect to the remote URL, simulating a POST, then capture the response and send it as your servlet's response. You might want to create a plain HTML page with a form that creates the POST you want, then trap the browser output so you can see what you have to simulate. There are several utilities available that will let you trap the browser output. I wrote one when I was doing a book on SOAP - You can download it from the bottom of this page.
thanks everyone ! William, I think using the HttpURLConnection is the best solution, however it seems a bit easier to just return an HTML page which sends the POST request from a form onLoad. Wicked tool, by the way ! cheers dennis
Author and all-around good cowpoke
Joined: Mar 22, 2000