Http proxy servlet

topic posted Mon, September 27, 2004 - 11:23 AM by  Edward
Share/Save/Bookmark
Advertisement
Hello
Is it possible to create a Http proxy using servlets?
posted by:
Edward
Advertisement
Advertisement
  • Unsu...
     

    Re: Http proxy servlet

    Mon, September 27, 2004 - 12:49 PM


    Absolutely. I've seen some sample source code but can't remember where at the moment. Maybe the O'Reilly Java Cookbook. I'm sure a little googling will come up with something.
  • Ken
    Ken
    offline 2

    Re: Http proxy servlet

    Mon, September 27, 2004 - 5:07 PM
    You can use the RequestDispatcher to forward to whatever source you want to. Easy to do.

    If you're wanting to do something with the request (decide where to send it) you might use Struts actions or Servlet filters.

    Ta.
  • Re: Http proxy servlet

    Tue, September 28, 2004 - 4:40 AM
    well I have a handle method(which does the proxy stuff) in a servlet that is called by doGet and doPost in my servlet, GET request proxy well but POST request always hang!!!.
    Talking about open source, well the code in the handle method was originally used in the jetty open source http server.
    I just readapted the code for the servlet api, my code hangs while accessing the response from the remote server, actaully when I try to copy the remote response headers(STATUS_CODE) to the HttpServletResponse headers which I will return to the client, below is the handle method. I am java.net.URLConnection api for communicating with remote server.
    Should I be using Sockets instead.
    I think I am missing some HTTP centric stuff in my code , please any healp will be sincerely appreciated .
    Thank you







    /**
    * @param request
    * @param response
    */
    private void handle( HttpServletRequest request,HttpServletResponse response )throws IOException
    {
    URLConnection connection;
    String resourceURL = getRequestedResourceURL(request);
    logger.info("Processing resource URL for client: "+ request.getRemoteAddr() + ", URL:" + resourceURL );
    //Is this a connect request?
    if(_CONNECT.equalsIgnoreCase(request.getMethod())){

    logger.info("Connect request from client: "+ request.getRemoteAddr());
    response.setHeader(__Connection,"close"); // XXX Needed for IE????
    handleConnect(request,response);
    return;

    }
    try
    {
    URL url = new URL(resourceURL);
    if(!isProxied(url)){
    return;
    }
    logger.info("Proxying resource URL for client: "+ request.getRemoteAddr());
    connection = url.openConnection();
    connection.setAllowUserInteraction(false);
    // Set method
    HttpURLConnection http=null;
    if(connection instanceof HttpURLConnection)
    {
    http=(HttpURLConnection)connection;
    http.setRequestMethod(request.getMethod());
    http.setInstanceFollowRedirects(false);
    }
    //check connection header
    String connectionHdr=request.getHeader(__Connection);
    if(connectionHdr!=null
    &&(connectionHdr.equalsIgnoreCase(__KeepAlive)||connectionHdr
    .equalsIgnoreCase("close")))
    connectionHdr=null;

    //copy headers
    boolean xForwardedFor=false;
    boolean hasContent=false;
    Enumeration enum=request.getHeaderNames();
    while(enum.hasMoreElements())
    {
    // XXX could be better than this!
    String hdr=(String)enum.nextElement();
    if(_DontProxyHeaders.containsKey(hdr))
    continue;
    if(connectionHdr!=null&&connectionHdr.indexOf(hdr)>=0)
    continue;
    if(__ContentType.equals(hdr))
    hasContent=true;
    Enumeration vals=request.getHeaders(hdr);
    while(vals.hasMoreElements())
    {
    String val=(String)vals.nextElement();
    if(val!=null)
    {
    logger.info("Copying HTTP header:" +hdr+" value: "+val);
    connection.addRequestProperty(hdr,val);
    xForwardedFor |= __XForwardedFor.equalsIgnoreCase(hdr);
    }
    }
    }
    logger.debug("Setting proxy header....");
    //Proxy headers
    connection.setRequestProperty("Via","1.1 (CarterraHttpProxyServlet)");
    if(!xForwardedFor)
    connection.addRequestProperty(__XForwardedFor,request.getRemoteAddr());
    //a little bit of cache control
    String cache_control=request.getHeader(__CacheControl);
    if(cache_control!=null&&(cache_control.indexOf("no-cache")>=0||cache_control.indexOf("no-store")>=0))
    connection.setUseCaches(false);
    // customize Connection
    customizeConnection(request,connection);
    //To be continued

    try{
    connection.setDoInput(true);
    // do input thang!
    logger.debug("Doing da input thang");
    InputStream in=request.getInputStream();
    if(hasContent)
    {
    connection.setDoOutput(true);
    copy(in,connection.getOutputStream(),-1);
    }
    // Connect
    connection.connect();
    logger.debug("Done da input thang");

    }
    catch(Exception e)
    {
    logger.error(e.getMessage());
    }
    InputStream proxy_in=null;
    // handler status codes etc.
    int code=__500_Internal_Server_Error;
    logger.debug("accessing return stream");
    if(http!=null)
    {
    logger.debug("Accessing HTTP error stream");
    proxy_in=http.getErrorStream();
    logger.debug("Accessing server response code");
    code=http.getResponseCode();
    logger.debug("Set response status code");
    response.setStatus(code);
    }
    logger.debug("Starting proxy stream ops");

    if(proxy_in==null)
    {
    try
    {
    logger.debug("Getting proxy input stream");
    proxy_in=connection.getInputStream();
    }
    catch(Exception e)
    {
    logger.error(e.getMessage());
    logger.debug("Some error occured:"+e.getClass().getName());
    proxy_in=http.getErrorStream();
    }
    }
    //clear response defaults
    logger.debug("Clearing response default headers");
    response.setHeader("Date",null);
    response.setHeader("Server",null);
    logger.debug("Cleared response default headers");


    // set response headers
    logger.debug("Setting response headers");
    int h=0;
    String hdr=connection.getHeaderFieldKey(h);
    String val=connection.getHeaderField(h);
    while(hdr!=null||val!=null)
    {
    if(hdr!=null&&val!=null&&!_DontProxyHeaders.containsKey(hdr))
    response.addHeader(hdr,val);
    logger.info("Building HTTP response header: " +hdr+" value:"+val);
    h++;
    hdr=connection.getHeaderFieldKey(h);
    val=connection.getHeaderField(h);

    }
    response.setHeader("Via","1.1 (CarterraHttpProxyServlet)");
    if(proxy_in!=null)
    logger.debug("Returning input stream back to client");
    copy(proxy_in,response.getOutputStream(),-1);

    } catch (Exception e){
    logger.warn(e.getMessage());
    if(!response.isCommitted())
    response.sendError(__400_Bad_Request);
    }

    }
  • Re: Http proxy servlet

    Tue, September 28, 2004 - 2:03 PM
    I have tried googling around and still nothing substantial comes up, and httpbridge.sourceforge.net has a problem with most free mail services,which is a major stopper for me.
    I am thinking of maybe using a webserver native solution, like inserting hooks into the webserver(Jetty) proxy code itself, but I would have loved to find a pure servlet solution.

Recent topics in "Java Monkeys"

Topic Author Replies Last Post
Javascripting costs Schirin 3 May 17, 2007
Design patterns and principles emblylan 6 February 14, 2007
open source hosting alternatives? Mark 2 February 3, 2007
Ruby > Java Unsubscribed 6 January 9, 2007