简体   繁体   中英

Python - sending http requests as strings

How can I send HTTP requests as string with python? something like this:

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

Assuming python 3, it is recommended that you use urllib.request . But since you specifically ask for providing the HTTP message as a string, I assume you want to do low level stuff, so you can also use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM