最近在使用python做介面測試,發現python中http請求方法有許多種,今天抽點時間把相關內容整理,分享給大家,具體內容如下:
python自備函式庫urllib2使用的比較多,簡單使用如下:
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()
這就是最簡單的urllib2發送post範例。程式碼比較多
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()
是不是覺得太複雜了。每次寫還得再翻文檔,看看第三種吧
發請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
以上是關於Python中http請求方法庫匯總的詳細內容。更多資訊請關注PHP中文網其他相關文章!