If you absolutely need to redirect the request, and not redirect (for example, if the remote URL is available only for the server, and not for the user), you can do your own redirect. In your servlet, you can send a request to a remote URL and write an InputStream from that request to an OutputStream in your servlet. You will obviously want to find and handle any errors with the request and make sure that the threads are closed properly. You will also need to manually redirect any parameters from the request to a new one.
The main approach:
URL url = new URL("http://www.externalsite.com/sample.html"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String postParams = "foo="+req.getParameter("foo"); DataOutputStream paramsWriter = new DataOutputStream(con.getOutputStream()); paramsWriter.writeBytes(postParams); paramsWriter.flush(); paramsWriter.close(); InputStream remoteResponse = conn.getInputStream(); OutputStream localResponder = resp.getOutputStream(); int c; while((c = remoteResponse.read()) != -1) localResponder.write(c); remoteResponse.close(); localResponder.close(); conn.disconnect();
This, obviously, does not handle the multiple request in your example, but gives you the basic idea of how to achieve what you want. I would recommend using Apache HTTP components to execute the request instead of HttpURLConnection, since it will simplify receiving a multi-page request with a file (I would suggest that you have to manually create the multipart / form-data body with HttpURLConnection). An example of the request can be found in How do I can I execute a POST request using multipart / form-data using Java? . An InputStream can be obtained from HttpEntity by calling getContent () (which would be equivalent to conn.getInputStream () in the example).
Writing an InputStream to an OutputStream can also be achieved using the Apache Commons IO IOUtils.copy () method.
EDIT: It may be possible to use req.getInputStream () to get the body of the raw request and write it to paramsWriter.writeBytes (), but I have not tried this, so there is no guarantee that it will work. I'm not sure what exactly contains req.getInputStream () for the mail request.
source share