How to forward the requestdispatcher to a remote URL

谁说我不能喝 提交于 2019-11-30 15:21:25
JB Nizet

You can't forward a request to a URL which is external to your webapp. You probably want to send a redirect to this URL instead. See HttpServletResponse.sendRedirect().

See Difference between JSP forward and redirect

Jonathan

If you absolutely need to forward the request as opposed to redirect (for instance, if the remote URL is only accessible to the server and not the user) it is possible to do your own forwarding. In your servlet, you can make a request to the remote URL and write the InputStream from that request to the OutputStream in your servlet. You would obviously want to look for and handle any errors with the request and make sure streams are closed properly, though. You would also need to manually forward any parameters from the request to the new one.

The basic approach would be:

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 doesn't handle the multipart request in your example, but it gives you a basic idea on how to achieve what you want. I'd recommend using Apache HTTP Components to do the request instead of HttpURLConnection since it will make the multipart request with the file easier to achieve (I'd imagine you'd have to manually create the multipart/form-data body with HttpURLConnection). An example of making the request can be found at How can I make a multipart/form-data POST request using Java?. An InputStream can be obtained from the HttpEntity by calling getContent() (which would be the equivalent to conn.getInputStream() in the example).

Writing the InputStream to the OutputStream can also be achieved more easily with Apache Commons IO IOUtils.copy() method.

EDIT: It may be possible to use req.getInputStream() to get the raw request body and write that to paramsWriter.writeBytes() but I have not tried this so there is no guarantee it would work. I'm not sure exactly what req.getInputStream() contains for a post request.

You cant forward to a different server.

You can use the resp.sendRedirect(url)

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendRedirect%28java.lang.String%29

method instead which will return a 302 redirect to the specified URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!