Java HTTP 代理服务器 [英] Java HTTP proxy server
问题描述
我需要实现一个 HTTP 代理服务器应用程序,它将来自多个客户端的请求代理到远程服务器.
I need to implement a HTTP proxy server application which will proxy requests from multiple clients to a remote server.
步骤如下:
- 客户端向代理转发请求
- 代理转发请求到服务器
- 服务器向代理返回请求
- 代理将请求返回给客户端.
我只是不确定我应该如何实现这个代理.我的第一个想法是实现一个 tomcat 应用程序,它使用 jersey/apache httpclient 将请求转发到远程服务器并将响应返回给客户端?
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.
推荐答案
你不能把它实现为 servlet,也没有理由使用任何形式的 HTTP 客户端.
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:
- 接受一个连接并为其启动一个线程.
- 读取来自客户端的请求直到空行.
- 提取 GET 或 CONNECT 命令或其他任何命令并连接到指定的主机.
- 如果失败,发回适当的 HTTP 错误响应,关闭套接字,然后忘记它.
否则启动两个线程来复制字节,每个方向一个.没什么好看的,就是
- 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);
}
或者使用 Apache SQUID.
Or use Apache SQUID.
这篇关于Java HTTP 代理服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!