0

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
4

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

how is the r variable used?
You can use request building methods on the connection object like putheader. See the linked documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.