gpt4 book ai didi

python - 通过Python套接字库发出的HTTP请求

转载 作者:行者123 更新时间:2023-12-03 11:53:43 24 4
gpt4 key购买 nike

我正在尝试通过Python套接字库向网站发出简单的HTTP GET请求。我在这里使用的示例网站是https://azlyrics.com/lyrics/charlieputh/attention.html。我的代码是:

from socket import *
serverName = 'azlyrics.com';
serverPort = 80;
clientSocket = socket(AF_INET, SOCK_STREAM);
print(clientSocket.connect((serverName, serverPort)));
message = '''GET /lyrics/charlieputh/attention.html HTTP/1.1
Host: www.azlyrics.com
Connection: keep-alive
''';
print(message);
clientSocket.send(message.encode());
modifiedMessage = clientSocket.recv(2048).decode();
print(modifiedMessage);
clientSocket.close();

但是我没有得到任何回应消息。另外,我从 connect()返回的对象是None。我已经使用Python请求库尝试了相同的URL,并且工作正常。我在这里做错了什么?

最佳答案

HTTP请求主体应以\r\n(CR-LF)结尾,

请尝试以下操作:

from socket import *
serverName = 'azlyrics.com';
serverPort = 80;
clientSocket = socket(AF_INET, SOCK_STREAM);
print(clientSocket.connect((serverName, serverPort)));
message = '''GET /lyrics/charlieputh/attention.html HTTP/1.1
Host: www.azlyrics.com
Connection: keep-alive


''';
print(message);
clientSocket.send(message.encode());
modifiedMessage = clientSocket.recv(2048).decode();
print(modifiedMessage);
clientSocket.close();

关于python - 通过Python套接字库发出的HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56618763/

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