简体   繁体   中英

Java proxy how to handle CONNECT requests

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.

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.

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

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

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?

The request should be whatever the client sends next after the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM