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())
請注意,我不建議您這樣做;這是一個非常令人討厭的黑客行為。盡管您明確表示不想解析原始請求字符串,但這絕對是正確的做法。
添加回答
舉報