Recently using python to do interface testing, I found that there are many http request methods in python. I will take some time to sort out the relevant content today and share it with you. Everyone, the specific content is as follows:
Python’s own library urllib2 is used more often, and the simple use is as follows:
import urllib2
response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')
print response.read()
import urllib2
import urllib
post_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 a post. There are a lot of codes
httplib is a relatively low-level http request module, and urlib is encapsulated based on httplib. The simple use is 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()
Simple get request
Let’s see if post request
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()
print requests.get('http://localhost:8080).text
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data=payload) print r.text
url = 'http://localhost:8080' r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin')) print r.status_code print r.headers print r.reason
import urllib params = urllib.urlencode({key:value,key:value}) resultHtml = urllib.urlopen('[API or 网址]',params) result = resultHtml.read() print result
The above is the detailed content of Summary of http request method libraries in Python. For more information, please follow other related articles on the PHP Chinese website!