Java HTTP 代理服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16451413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java HTTP proxy server
提问by Alistair walsh
I need to implement a HTTP proxy server application which will proxy requests from multiple clients to a remote server.
我需要实现一个 HTTP 代理服务器应用程序,它将来自多个客户端的请求代理到远程服务器。
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 ?
我只是不确定我应该如何实现这个代理。我的第一个想法是实现一个 tomcat 应用程序,它使用 jersey/apache httpclient 将请求转发到远程服务器并将响应返回给客户端?
Is there a better way to implement such a proxy server ?
有没有更好的方法来实现这样的代理服务器?
The proxy would need to handle multiple threads.
代理需要处理多个线程。
回答by user207421
You can't implement it as a servlet, and there is no reason to use any form of HTTP client.
您不能将其实现为 servlet,也没有理由使用任何形式的 HTTP 客户端。
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.
- 接受一个连接并为其启动一个线程。
- 读取来自客户端的请求直到空行。
- 提取 GET 或 CONNECT 命令或其他任何命令并连接到指定的主机。
- 如果失败,发送回适当的 HTTP 错误响应,关闭套接字,然后忘记它。
否则启动两个线程来复制字节,每个方向一个。没什么好看的,就是
while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); }
- 当其中一个套接字读取 EOS 时,关闭另一个套接字以进行输出并退出获取 EOS 的线程。
- 如果作为 EOS 源的套接字已经关闭以进行输出,请将它们都关闭。
Or use Apache SQUID.
或者使用 Apache SQUID。
回答by Ilya Yevlampiev
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.
查看LittleProxy—— 它具有用于传入和传出请求的内置类;您可以像在 servlet 中处理 HTTP 请求一样编写代码。