Java HTTP 代理服务器 [英] Java HTTP proxy server

查看:35
本文介绍了Java HTTP 代理服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个 HTTP 代理服务器应用程序,它将来自多个客户端的请求代理到远程服务器.

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

步骤如下:

  1. 客户端向代理转发请求
  2. 代理转发请求到服务器
  3. 服务器向代理返回请求
  4. 代理将请求返回给客户端.

我只是不确定我应该如何实现这个代理.我的第一个想法是实现一个 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:

  1. 接受一个连接并为其启动一个线程.
  2. 读取来自客户端的请求直到空行.
  3. 提取 GET 或 CONNECT 命令或其他任何命令并连接到指定的主机.
  4. 如果失败,发回适当的 HTTP 错误响应,关闭套接字,然后忘记它.
  5. 否则启动两个线程来复制字节,每个方向一个.没什么好看的,就是

  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);
}

  • 当其中一个套接字读取 EOS 时,关闭另一个套接字以进行输出并退出获取 EOS 的线程.
  • 如果作为 EOS 源的套接字已经关闭以进行输出,请将它们都关闭.
  • 或者使用 Apache SQUID.

    Or use Apache SQUID.

    这篇关于Java HTTP 代理服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆