Python以字符串形式发送http请求

2024-04-27 04:00:56 发布

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

如何使用python以字符串形式发送HTTP请求?像这样:

r = """GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.stackoverflow.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive"""

answer = send(r)
print answer  #  gives me the response as string

Tags: 字符串answerhttphostmozillahellogetwindows
1条回答
网友
1楼 · 发布于 2024-04-27 04:00:56

假设使用python3,建议您使用urllib.request。 但是由于您特别要求以字符串形式提供HTTP消息, 我假设你想做一些低级的事情,所以你也可以使用http.client

import http.client
connection = http.client.HTTPConnection('www.python.org')

connection.request('GET', '/')
response = connection.getresponse()
print(response.status)
print(response.msg)
answer = response.read()
print(answer)

相关问题 更多 >