Search code examples
javaservletsurlconnection

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.setRequestProperty to set the header fields to what they are in the incoming request to servlet.


Solution

  • i think you are looking for

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