欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中http請(qǐng)求方法庫(kù)匯總

 更新時(shí)間:2016年01月06日 16:12:19   作者:Believer007  
最近在使用python做接口測(cè)試,發(fā)現(xiàn)python中http請(qǐng)求方法有許多種,今天抽點(diǎn)時(shí)間把相關(guān)內(nèi)容整理,對(duì)python http請(qǐng)求相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧

最近在使用python做接口測(cè)試,發(fā)現(xiàn)python中http請(qǐng)求方法有許多種,今天抽點(diǎn)時(shí)間把相關(guān)內(nèi)容整理,分享給大家,具體內(nèi)容如下所示:

一、python自帶庫(kù)----urllib2

python自帶庫(kù)urllib2使用的比較多,簡(jiǎn)單使用如下:

import urllib2
response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')
print response.read() 

簡(jiǎn)單的get請(qǐng)求

import urllib2
import urllib
post_data = urllib.urlencode({})
response = urllib2.urlopen('http://localhost:8080/, post_data)
print response.read()
print response.getheaders() 

這就是最簡(jiǎn)單的urllib2發(fā)送post例子。代碼比較多

二、python自帶庫(kù)--httplib

httplib是一個(gè)相對(duì)底層的http請(qǐng)求模塊,urlib就是基于httplib封裝的。簡(jiǎn)單使用如下:

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() 

簡(jiǎn)單的get請(qǐng)求

我們?cè)賮?lái)看post請(qǐng)求

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() 

是不是覺(jué)得太復(fù)雜了。每次寫(xiě)還得再翻文檔,看看第三種吧

三、第三方庫(kù)--requests

發(fā)請(qǐng)get請(qǐng)求超級(jí)簡(jiǎn)單:

print requests.get('http://localhost:8080).text 

就一句話,再來(lái)看看post請(qǐng)求

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text 

也很簡(jiǎn)單。

再看看如果要認(rèn)證:

url = 'http://localhost:8080'
r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin'))
print r.status_code
print r.headers
print r.reason 

是不是比urllib2更簡(jiǎn)單多了吧,且requests自帶json解析。這點(diǎn)非常棒

python中的http請(qǐng)求

import urllib
params = urllib.urlencode({key:value,key:value})
resultHtml = urllib.urlopen('[API or 網(wǎng)址]',params)
result = resultHtml.read()
print result

相關(guān)文章

最新評(píng)論