3 回答
TA贡献2037条经验 获得超6个赞
库 ( urllib2/urllib, httplib/urllib, Requests) 被封装以方便高级使用。
如果你想发送格式化的HTTP请求文本,你应该考虑Python套接字库。
有一个套接字示例:
import socket
get_str = 'GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36\r\nAccept: */*\r\n\r\n'%("/", "www.example.com")
def get(hostname, port):
sock = socket.socket()
sock.connect((hostname, port))
b_str = get_str.encode("utf-8")
sock.send(b_str)
response = b''
temp = sock.recv(4096)
while temp:
temp = sock.recv(4096)
response += temp
return response.decode(encoding="utf-8")
res = get(hostname="www.example.com", port=80)
print(res)
TA贡献1821条经验 获得超6个赞
如果您真的非常愿意,您可以欺骗http.client.HTTPSConnection(或http.client.HTTPConnection对于普通的 HTTP 连接)做您想做的事情。这是Python 3代码;在Python 2中应该可以使用不同的导入和常规字符串而不是字节。
import http.client
# Requesting https://api.ipify.org as a test
client = http.client.HTTPSConnection('api.ipify.org')
# Send raw HTTP. Note that the docs specifically tell you not to do this
# before the headers are sent.
client.send(b'GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n')
# Trick the connection into thinking a request has been sent. We are
# manipulating the name-mangled __state attribute of the connection,
# which is very, very ugly.
client._HTTPConnection__state = 'Request-sent'
response = client.getresponse()
# should print the response body as bytes, in this case e.g. b'123.10.10.123'
print(response.read())
请注意,我不建议您这样做;这是一个非常令人讨厌的黑客行为。尽管您明确表示不想解析原始请求字符串,但这绝对是正确的做法。
添加回答
举报