Summary of http request library and python request library in python
I recently used python for interface testing and found that there are many http request methods in python, which are summarized as follows:
1. python built-in library ---- urllib2
The python built-in library urllib2 is used in many ways and is easy to use as follows:
import urllib2response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')print response.read()
Simple get request
import urllib2import urllibpost_data = urllib.urlencode({})response = urllib2.urlopen('http://localhost:8080/, post_data)print response.read()print response.getheaders()
This is the simplest example of urllib2 sending post. Many codes
Ii. python built-in library -- httplib
Httplib is a relatively underlying http request module, and urlib is encapsulated based on httplib. Simple use:
import httplibconn = httplib.HTTPConnection("www.python.org")conn.request("GET", "/index.html")r1 = conn.getresponse()print r1.status, r1.reasondata1 = r1.read()conn.request("GET", "/parrot.spam")r2 = conn.getresponse()data2 = r2.read()conn.close()
Simple get request
Let's look at the post request.
import httplib, urllibparams = 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 dataconn.close()
Is it too complicated. I have to repeat the document every time I write it. Let's take a look at the third type.
Iii. Third-party database-requests
Sending a get request is super simple:
print requests.get('http://localhost:8080).text
Let's take a look at the post request.
payload = {'key1': 'value1', 'key2': 'value2'}r = requests.post("http://httpbin.org/post", data=payload)print r.text
It is also very simple.
Let's see if you want to authenticate:
url = 'http://localhost:8080'r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin'))print r.status_codeprint r.headersprint r.reason
Is it simpler than urllib2, and requests comes with json parsing. This is awesome.
For more details, refer to the python documentation as follows:
Urllib2: https://docs.python.org/2/library/urllib2.html
Httplib: https://docs.python.org/2/library/httplib.html? Highlight = httplib
Requests: http://www.python-requests.org/en/latest/