Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HTTP proxy server [closed]

I need to implement a HTTP proxy server application which will proxy requests from multiple clients to a remote server.

Here are the steps:

  1. Client forward request to proxy
  2. Proxy forward request to server
  3. Server returns request to Proxy
  4. Proxy returns request to Client.

I'm just not sure how I should implement this proxy. My first thought was to implement a tomcat application which uses jersey / apache httpclient to forward the request to the remote server and return the response back to the client ?

Is there a better way to implement such a proxy server ?

The proxy would need to handle multiple threads.

like image 404
Alistair walsh Avatar asked May 08 '13 22:05

Alistair walsh


2 Answers

You can't implement it as a servlet, and there is no reason to use any form of HTTP client.

A featureless proxy server is a really simple thing:

  1. Accept a connection and start a thread for it.
  2. Read the request from the client up to the blank line.
  3. Extract the GET or CONNECT command or whatever it is and connect to the named host.
  4. If that fails, send back an appropriate HTTP error response, close the socket, and forget about it.
  5. Otherwise start two threads to copy bytes, one in each direction. Nothing fancy, just

    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    
  6. When one of those sockets reads an EOS, shutdown the other socket for output and exit the thread that got the EOS.
  7. If the socket that was the source of the EOS is already shutdown for output, close them both.

Or use Apache SQUID.

like image 153
user207421 Avatar answered Nov 03 '22 11:11

user207421


Check out LittleProxy -- it has built-in classes for incoming and outgoing requests; you can just write your code similarly to how you would handle a HTTP request in a servlet.

like image 41
Ilya Yevlampiev Avatar answered Nov 03 '22 11:11

Ilya Yevlampiev