gpt4 book ai didi

Python 套接字模块。连接到 HTTP 代理然后对外部资源执行 GET 请求

转载 作者:可可西里 更新时间:2023-11-01 16:24:26 25 4
gpt4 key购买 nike

首先,我知道还有其他模块(例如 Requests)更适合且使用起来更简单,但我想使用 socket 模块来更好地理解 HTTP。

我有一个执行以下操作的简单脚本:

客户端 ---> HTTP 代理 ---> 外部资源 (GET Google.com)

我能够正常连接到 HTTP 代理,但是当我将 google.com 的 GET 请求 header 发送到代理时,它根本没有给我任何响应。

#!/usr/bin/python
import socket
import sys



headers = """GET / HTTP/1.1\r\n
Host: google.com\r\n\r\n"""



socket = socket

host = "165.139.179.225" #proxy server IP
port = 8080 #proxy server port

try:
s = socket.socket()
s.connect((host,port))
s.send(("CONNECT {0}:{1} HTTP/1.1\r\n" + "Host: {2}: {3}\r\n\r\n").format(socket.gethostbyname(socket.gethostname()),1000,port,host))
print s.recv(1096)
s.send(headers)
response = s.recv(1096)
print response
s.close()
except socket.error,m:
print str(m)
s.close()
sys.exit(1)

最佳答案

要向代理发出 HTTP 请求,请打开到代理服务器的连接,然后发送 HTTP 代理请求。此请求与普通 HTTP 请求基本相同,但包含绝对 URL 而不是相对 URL,例如

 > GET http://www.google.com HTTP/1.1
> Host: www.google.com
> ...

< HTTP response

要使 HTTPS 请求使用 CONNECT 方法打开隧道,然后在该隧道内正常进行,即进行 SSL 握手,然后在隧道内进行正常的非代理请求,例如

 > CONNECT www.google.com:443 HTTP/1.1
>
< .. read response to CONNECT request, must be 200 ...

.. establish the TLS connection inside the tunnel

> GET / HTTP/1.1
> Host: www.google.com

关于Python 套接字模块。连接到 HTTP 代理然后对外部资源执行 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com