Hello,
I need to write a servlet that accepts GET and POST requests and forwards
the request to the URL in the request-parameter "url".
A very simple implementation looks like this:
---
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ProxyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException
{
doRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException
{
doRequest(request, response);
}
public void doRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException,
MalformedURLException
{
URL url = new URL(request.getParameter("url"));
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int c;
while ((c = is.read()) != -1)
{
out.write(c);
}
is.close();
return;
}
}
---
A call to "http://www.domain.com/servlet/ProxyServlet?
url=http://www.other_domain.com/path/to/webpage.htm" results in a call
to "http://www.other_domain.com/path/to/webpage.htm" by the ProxyServlet.
The resulting page is then copied in the HttpServletResponse-object of the
ProxyServlet (and send to the calling application, for instance a browser
window). Of course, I would like to forward the header-parameters, request-
parameters etc. as well (which is not done in my code).
Thus, my questions are:
Is there a class which does this already? It is hard to believe this has
not been done before.
What is this called? A ProxyServlet, TunnelServlet, GatewayServlet or even
something else?
Thanks,
Joeri