Python 如何調(diào)用遠(yuǎn)程接口

在python中我們可以使用requests模塊來(lái)實(shí)現(xiàn)調(diào)用遠(yuǎn)程接口
一、安裝requests模塊
pip?install?requests
二、使用requests模塊實(shí)現(xiàn)get方式調(diào)用遠(yuǎn)程接口
使用get方式調(diào)用遠(yuǎn)程接口主要使用了requests模塊的get方法
requests.get()
get方法常見(jiàn)的參數(shù)有url,params和headers
url:表示遠(yuǎn)程接口的地址
params表示get參數(shù)
headers表示get傳參的headers參數(shù)信息
使用requests模塊實(shí)現(xiàn)get方式調(diào)用遠(yuǎn)程接口的簡(jiǎn)單實(shí)現(xiàn)如下
#?-*-?coding:?utf-8?-*-
import?requests
import?ast
#接口地址
url?=?'XXX'
#get傳參
data?=?{'type':'0'}
#headers信息
headers?=?{
??'Content-Type':?'application/x-www-form-urlencoded',
??'Authorization':?'Bearer?XXX'
}
#
r?=?requests.get(url,?params=data,?headers?=?headers)
#?接口返回的狀態(tài)碼
print(r.status_code)
#?接口返回的字符串內(nèi)容
content?=?r.text
#?#將字符串轉(zhuǎn)字典型
content_list?=?ast.literal_eval(content)
print(content_list)
#?接口返回的json格式內(nèi)容
print(r.json())
根據(jù)如上就可以實(shí)現(xiàn)使用get方式調(diào)用遠(yuǎn)程接口
三、使用requests模塊實(shí)現(xiàn)post方式調(diào)用遠(yuǎn)程接口
使用post方式調(diào)用遠(yuǎn)程接口主要使用了requests模塊的post方法
requests.post()
post方法常見(jiàn)的參數(shù)有url,data和headers
url:表示遠(yuǎn)程接口的地址 data:表示post參數(shù) headers:表示post傳參的headers參數(shù)信息
使用requests模塊實(shí)現(xiàn)post方式調(diào)用遠(yuǎn)程接口的簡(jiǎn)單實(shí)現(xiàn)如下
#?-*-?coding:?utf-8?-*-
import?requests
import?ast
#接口地址
url?=?'XXX'
#header信息
headers?=?{
??'Content-Type':?'application/x-www-form-urlencoded',
??'Authorization':?'Bearer?XXX'
}
#post傳參
data?=?{
??'nickname':?'111',
??'gender':?1,
??'city':?'ce',
??'avatar':?'111'
}
r?=?requests.post(url,?data=data,headers=headers)
#?接口返回的狀態(tài)碼
print(r.status_code)
#?接口返回的字符串內(nèi)容
content?=?r.text
#?#將字符串轉(zhuǎn)字典型
content_list?=?ast.literal_eval(content)
print(content_list)
#?接口返回的json格式內(nèi)容
print(r.json())
(完)
評(píng)論
圖片
表情
