最近在使用python做介面測試,發現python中http請求方法有許多種,今天抽點時間把相關內容整理,分享給大家,具體內容如下所示:
一、python自帶庫----urllib2
python自帶庫urllib2使用的比較多,簡單使用如下:
import urllib2
response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')
print response.read()
簡單的get請求
import urllib2
import urllib
post_data = urllib.urlencode({})
response = urllib2.urlopen('http://localhost:8080/, post_data)
print response.read()
print response.getheaders()
這就是最簡單的urllib2傳送post例子。程式碼比較多
二、python自帶庫--httplib
httplib是一個相對底層的http請求模組,urlib就是基於httplib封裝的。簡單使用如下:
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()
簡單的get請求
我們再來看post請求
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()
是不是覺得太複雜了。每次寫還得再翻文件,看看第三種吧
三、第三方庫--requests
發請get請求超級簡單:
print requests.get('http://localhost:8080).text
就一句話,再來看看post請求
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
是不是比urllib2更簡單多了吧,且requests自帶json解析。這點非常棒
python中的http請求
import urllib params = urllib.urlencode({key:value,key:value}) resultHtml = urllib.urlopen('[API or 網址]',params) result = resultHtml.read() print result