Recently in the use of Python interface testing, found Python in the HTTP request method There are many kinds of, today take some time to organize the relevant content, to share with you, the specific content is as follows:
One, Python comes with library----URLLIB2
Python comes with a library urllib2 used more, simple to use as follows:
This is the simplest urllib2 send post example. More code
Ii. python comes with library--httplib
Httplib is a relatively low-level HTTP request module, Urlib is based on httplib encapsulation. Simple to use as follows:
Import Httplib
conn = Httplib. Httpconnection ("www.python.org")
Conn.request ("GET", "/index.html")
R1 = Conn.getresponse ()
Print R1.status, R1.reason
Data1 = R1.read ()
Conn.request ("GET", "/parrot.spam")
r2 = Conn.getresponse ()
Data2 = R2.read ()
Conn.close ()
A simple GET request
Let's look at the POST request again
Import Httplib, Urllib
params = Urllib.urlencode ({' @number ': 12524, ' @type ': ' Issue ', ' @action ': ' Show '})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "Text/plain"}
conn = Httplib. Httpconnection ("bugs.python.org")
Conn.request ("POST", "", params, headers)
Response = Conn.getresponse ()
data = Response.read ()
Print data
Conn.close ()
I think it's too complicated. Every time you write, you have to go through the document again, look at the third.
Iii. third-party library--requests
Sending a GET request is super simple:
Print Requests.get (' http://localhost:8080). Text
Just a word, then look at the POST request
Payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '}
r = Requests.post ("Http://httpbin.org/post", Data=payload)
Print R.text
Also very simple.
Look again if you want to certify:
url = ' http://localhost:8080 '
r = Requests.post (URL, data={}, Auth=httpbasicauth (' admin ', ' admin '))
Print R.status_code
Print R.headers
Print R.reason
Is it much simpler than URLLIB2, and the requests comes with JSON parsing. This is great.
HTTP requests in Python
Import Urllib
params = Urllib.urlencode ({key:value,key:value})
resulthtml = Urllib.urlopen (' [API or URL] ', params)
result = Resulthtml.read ()
Print result
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service