Java代理如何处理CONNECT请求 [英] Java proxy how to handle CONNECT requests

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

问题描述

我是网络编程的新手,我正在尝试在Java中实现一个简单的http代理,它应该转发客户端的请求并转回响应。

I am new to network programming and I am trying to implement a simple http proxy in Java that is just supposed to forward the client's requests and transfer back the response.

要处理GET请求,我只需读取客户端套接字InputStream,创建一个到所需主机(我从套接字读取)的新套接字,然后将客户端完成的相同GET请求写入此新套接字的OutputStream。同样要检索响应,我将主机套接字的InputStream的响应写回到客户端套接字的OutputStream。

To handle GET requests I simply read the client socket InputStream, create a new socket to the desired host (that I read from the socket) to then write the same GET request done by the client to the OutputStream of this new socket. Same thing to retrieve the response, I write back the response from the InputStream of the host socket to the OutputStream of the client socket.

但是当我遇到麻烦时必须处理CONNECT请求,例如,当我尝试从浏览器访问www.google.com时,这会导致从客户端套接字读取此信息:

But I am having some troubles when I have to handle CONNECT requests, for instance, when I try to access www.google.com from my browser, this results in reading this from the client socket:

CONNECT www.google.com:443 HTTP/1.1
Host: www.google.com
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

根据我的理解,我应该通过端口443连接到主机www.google.com。所以我创建了一个新套接字:

To my understanding, I should connect to the host www.google.com on port 443. So I create a new socket :

Socket socket = new Socket(www.google.fr, 443);

但请求应该是什么?我只是试过:

But what should be the request? I simply tried:

GET / HTTP/1.1

但是使用Wireshark,似乎主机通过发送回FIN和RST TCP段来立即终止连接。

But using Wireshark, it seems that the host immediately terminates the connection by sending back FIN and RST TCP segments.

如何我应该继续正确处理这些请求并检索网页的内容吗?

How should I proceed to correctly handle these requests and retrieve the content of the webpage?

推荐答案

请求应该被任何客户端发送CONNECT之后下一个。

The request should be whatever the client sends next after the CONNECT.

您必须使用HTTP状态行响应CONNECT请求,然后您真正需要做的就是开始双向复制字节。您无需进一步关注请求和响应。

You have to respond to the CONNECT request with an HTTP status line, then really all you have to do is start copying bytes in both directions. You don't need to care about the request and the response any further.

这篇关于Java代理如何处理CONNECT请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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