开发者

copying the request header from request object to urlConnection object

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.setReque开发者_Go百科stProperty to set the header fields to what they are in the incoming request to servlet.


i think you are looking for

RequestDispatcher rd;
rd = getServletContext().getRequestDispatcher("pathToServlet");
rd.forward(request, response);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜