HTTP/1.1与HTTP/1.0 Python s

2024-04-23 14:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python套接字发送和接收HTTP数据。但是当我使用HTTP/1.0的时候它工作了,但是当我使用HTTP/1.1的时候它只是一直在等待。。。你知道吗

此代码有效

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('httpbin.org', 80)
client_socket.connect(server_address)

request_header = 'GET /ip HTTP/1.0\r\nHost: httpbin.org\r\n\r\n'
client_socket.send(request_header.encode())

response = ''
while True:
    recv = client_socket.recv(1024)
    if not recv:
        break
    response += recv 

print(response)
client_socket.close()

这不管用

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('httpbin.org', 80)
client_socket.connect(server_address)

request_header = 'GET /ip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n'
client_socket.send(request_header.encode())

response = ''
while True:
    recv = client_socket.recv(1024)
    if not recv:
        break
    response += recv 

print(response)
client_socket.close() 

如果HTTP/1.1是问题所在,那么如何检测它是否不支持HTTP/1.1?你知道吗


Tags: orgimportclienthttpserveraddressresponserequest
1条回答
网友
1楼 · 发布于 2024-04-23 14:07:29

HTTP/1.1默认为持久连接。如果希望服务器在发送响应后关闭连接,则需要发送Connection: close头。你知道吗

request_header = 'GET /ip HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n'

相关问题 更多 >