I need to implement a HTTP proxy server application which will proxy requests from multiple clients to a remote server.
Here are the steps:
- Client forward request to proxy
- Proxy forward request to server
- Server returns request to Proxy
- 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.
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:
- Accept a connection and start a thread for it.
- Read the request from the client up to the blank line.
- Extract the GET or CONNECT command or whatever it is and connect to the named host.
- If that fails, send back an appropriate HTTP error response, close the socket, and forget about it.
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);
}
- When one of those sockets reads an EOS, shutdown the other socket for output and exit the thread that got the EOS.
- If the socket that was the source of the EOS is already shutdown for output, close them both.
Or use Apache SQUID.
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.