views:

52

answers:

2
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    URL url = new URL("http://localhost:8080/testy/Out");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");    
    PrintWriter out = response.getWriter();
    for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
        Object o = e.nextElement();
        String value = request.getHeader(o.toString());
        out.println(o + "--is--" + value + "<br>");
        connection.setRequestProperty((String) o, value);
    }
    connection.connect();
}

i wrote the above code in a servlet to post form so some alternate locations than this servlet,but its not working.is it okay to use connection.setRequestProperty to set the header fields to what they are in the incoming request to servlet.

+1  A: 

i think you are looking for

RequestDispatcher rd;
rd = getServletContext().getRequestDispatcher("pathToServlet");
rd.forward(request, response);
Oliver Michels
no actually i was trying to fetch some remote url with the headers of the current request .
Bunny Rabbit
Or afterwards actually not..? Else it seems wrong to set it as accepted.
BalusC
+1  A: 

URLConnection is lazily executed. That is, it won't actually fire the HTTP request until you grab some information about the HTTP response. E.g.

int responseCode = httpUrlConnection.getResponseCode();

or

InputStream responseBody = urlConnection.getInputStream();

or

String statusHeader = urlConnection.getHeaderField(null);

The connection.connect(); is by the way entirely superfluous. It's already executed at the moment you called url.openConnection();. Also the connection.setRequestMethod("POST"); is entirely superflous, the connection.setDoOutput(true) already does that.

That said, if the target is actually located in the same webapp context hosted at the same machine, then there are much better ways to invoke it than creating a HTTP connection to it, such as forwarding or redirecting the request.

BalusC
Yeah it worked after adding a line connectin.getHeaderField();
Bunny Rabbit
<Quote>"The connection.connect(); is by the way entirely superfluous"</Quote>I guess connection.openConnection() lets one Manipulate parameters that affect the connection to the remote resource. while connection.connect() is to Interact with the resource; query header fields and contents after the connection.http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html
Bunny Rabbit
That's true, but it is still superflous in case of HTTP connections. Leave it away and you'll see that it just works.
BalusC