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. Today I will take some time to sort out and share the relevant content with you. The specific content is 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.
Http requests in python
Import urllibparams = urllib. urlencode ({key: value, key: value}) resultHtml = urllib. urlopen ('[API or url]', params) result = resultHtml. read () print result
Articles you may be interested in:
- Example of code for using urllib2 in python to obtain the http Request status code
- How to solve the problem of incomplete receiving of HTTP request data using socket in Python
- Python uses urllib2 to submit an http post request
- Python uses get and post methods to send http requests and receive http responses
- Summary of how python sends HTTP requests