国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果

這篇具有很好參考價(jià)值的文章主要介紹了Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

一、Post請(qǐng)求

1、使用python發(fā)送一個(gè)Post請(qǐng)求

有時(shí)候遇到請(qǐng)求url中有很多參數(shù)。

1.1 示例1

accounts和pwd請(qǐng)到http://shop-xo.hctestedu.com/注冊(cè)。

import requests

# 請(qǐng)求體
data = {
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 只有php項(xiàng)目需要application和application_client_type
# 寫法一, 在請(qǐng)求Url中帶上所有參數(shù),application和application_client_type,用&隔開
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                                "s=api/user/login"
                                "&application=app"
                                "&applicaiton_client_type=weixin", json=data)

# 輸出響應(yīng)結(jié)果
print(response.text)

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"id":"7073","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"189","locking_integral":"0","referrer":"0","add_time":"1646195490","add_time_text":"2022-03-02 12:31:30","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxxx"}}

1.2 示例2

使用不定長(zhǎng)參數(shù) params,將url中需要的參數(shù)單獨(dú)封裝。

import requests

# 請(qǐng)求體
data = {
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定長(zhǎng)參數(shù)params
param_data = {
    "application": "app",
    "application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 輸出響應(yīng)結(jié)果
print(response.text)

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}

二、獲取Response body

1、response.text

用type()查看response.text的類型,是str

import requests

# 請(qǐng)求體
data = {
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定長(zhǎng)參數(shù)params
param_data = {
    "application": "app",
    "application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 輸出響應(yīng)結(jié)果
print(response.text)
print(type(response.text))

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
<class 'str'>

2、response.json()

用type()查看response.json()的類型,是dict

import requests

# 請(qǐng)求體
data = {
    "accounts": "xx",
    "pwd": "xxx",
    "type": "username"
}

# 使用不定長(zhǎng)參數(shù)params
param_data = {
    "application": "app",
    "application_client_type": "weixin"
}
# 寫法2:使用不定長(zhǎng)參數(shù)params
response = requests.post(url="http://shop-xo.hctestedu.com/index.php?"
                             "s=api/user/login", params=param_data, json=data)

# 輸出響應(yīng)結(jié)果
print(response.json())
print(type(response.json()))

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xx","is_mandatory_bind_mobile":0,"token":"xxxxx"}}
<class 'dict'>

三、獲取響應(yīng)狀態(tài)碼:res.status_code

print(response.status_code)

執(zhí)行結(jié)果:

200

更多狀態(tài)碼:

狀態(tài)代碼有三位數(shù)字組成,第一個(gè)數(shù)字定義了響應(yīng)的類別,共分五種類別:
1xx:指示信息--表示請(qǐng)求已接收,繼續(xù)處理
2xx:成功--表示請(qǐng)求已被成功接收、理解、接受
3xx:重定向--要完成請(qǐng)求必須進(jìn)行更進(jìn)一步的操作
4xx:客戶端錯(cuò)誤--請(qǐng)求有語法錯(cuò)誤或請(qǐng)求無法實(shí)現(xiàn)
5xx:服務(wù)器端錯(cuò)誤--服務(wù)器未能實(shí)現(xiàn)合法的請(qǐng)求

常見狀態(tài)碼:
200 OK	//客戶端請(qǐng)求成功
400 Bad Request	//客戶端請(qǐng)求有語法錯(cuò)誤,不能被服務(wù)器所理解
401 Unauthorized	//請(qǐng)求未經(jīng)授權(quán),這個(gè)狀態(tài)代碼必須和WWW-Authenticate報(bào)頭域一起使用
403 Forbidden	//服務(wù)器收到請(qǐng)求,但是拒絕提供服務(wù)
404 Not Found	//請(qǐng)求資源不存在,eg:輸入了錯(cuò)誤的URL
500 Internal Server Error	//服務(wù)器發(fā)生不可預(yù)期的錯(cuò)誤
503 Server Unavailable	//服務(wù)器當(dāng)前不能處理客戶端的請(qǐng)求,一段時(shí)間后可能恢復(fù)正常

四、獲取響應(yīng)cookies:res.cookies

print(response.cookies)

執(zhí)行結(jié)果:

<RequestsCookieJar[<Cookie PHPSESSID=92ppj01t00t4v142rd8fsmos7k for shop-xo.hctestedu.com/>]>

五、獲取響應(yīng)headers:res.headers

print(response.headers)

執(zhí)行結(jié)果:

{'Server': 'nginx', 'Date': 'Sun, 05 Mar 2023 10:04:02 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Cookie': 'PHPSESSID=ul9qsgallg17d5am81q08pfhj0; path=/; HttpOnly', 'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache'}

六、獲取響應(yīng)結(jié)果原始內(nèi)容:res.content

content,沒有經(jīng)過編譯的,以字節(jié)的形式展示。而上述提到的text是編譯過的。自動(dòng)找到請(qǐng)求頭中的編碼格式,進(jìn)行解析。

print(response.content)
print(type(response.content))

執(zhí)行結(jié)果:

b'{"msg":"\xe7\x99\xbb\xe5\xbd\x95\xe6\x88\x90\xe5\x8a\x9f","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}'
<class 'bytes'>

content還支持手動(dòng)的編碼,例如使用utf-8編碼,編碼后的是str類型,json本質(zhì)是一種字符串類型

resp = response.content.decode("utf-8")
print(resp)
print(type(resp))

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}
<class 'str'>

七、獲取響應(yīng)結(jié)果:最原生的狀態(tài),對(duì)象在內(nèi)存中的地址:res.raw

print(response.raw)
print(type(response.raw))

執(zhí)行結(jié)果:

<urllib3.response.HTTPResponse object at 0x0000023317D8D880>
<class 'urllib3.response.HTTPResponse'>

八、解析響應(yīng)數(shù)據(jù)

響應(yīng)數(shù)據(jù)如下:

{
    "msg": "登錄成功",
    "code": 0,
    "data": {
        "id": "22299",
        "username": "Summer",
        "nickname": "",
        "mobile": "",
        "email": "",
        "avatar": "http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg",
        "alipay_openid": "",
        "weixin_openid": "",
        "weixin_unionid": "",
        "weixin_web_openid": "",
        "baidu_openid": "",
        "toutiao_openid": "",
        "qq_openid": "",
        "qq_unionid": "",
        "integral": "0",
        "locking_integral": "0",
        "referrer": "0",
        "add_time": "1678005098",
        "add_time_text": "2023-03-05 16:31:38",
        "mobile_security": "",
        "email_security": "",
        "user_name_view": "chengcheng",
        "is_mandatory_bind_mobile": 0,
        "token": "d653d78ac417f65e1cd38c6f3e220341"
    }
}

通常我們獲取響應(yīng)數(shù)據(jù)后,是需要進(jìn)行結(jié)果驗(yàn)證的。例如,我想從登錄接口的響應(yīng)中拿到token,供后面的接口請(qǐng)求鑒權(quán)使用。

1、字典方式解析及其缺點(diǎn)

上面已經(jīng)講到,可以使用response.json()方法拿到一個(gè)字典。既然是字典,就可以用處理字典的方式來獲取某個(gè)字段的值。

resp = response.json()
token = resp["data"]["token"]
print(token )

執(zhí)行結(jié)果:

d653d78ac417f65e1cd38c6f3e220341

字典解析的缺點(diǎn):如果接口數(shù)據(jù)異常,響應(yīng)體缺少某個(gè)字段,就會(huì)發(fā)生keyerror,導(dǎo)致程序異常。

resp = response.json()
token = resp["data"]["token1"]
print(token )

執(zhí)行結(jié)果:

Traceback (most recent call last):
  File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 128, in <module>
    token = resp["data"]["token1"]
KeyError: 'token1'

2、Jsonpath表達(dá)式解析及其優(yōu)點(diǎn)

上面的響應(yīng)body結(jié)構(gòu)比較簡(jiǎn)單,如果我們要解析特別復(fù)雜的響應(yīng)體,通過字典方式就很復(fù)雜。這個(gè)時(shí)候更推薦jsonpath。需要引入jsonpath庫(kù)。

import jsonpath

resp = response.json()  # 將返回值轉(zhuǎn)換成字典格式
token = jsonpath.jsonpath(resp, '$..token')  # token的jsonpath表達(dá)式:$..token
print(token)

執(zhí)行結(jié)果:

['d653d78ac417f65e1cd38c6f3e220341']

通過結(jié)果來看,獲取到的token是只有一個(gè)元素的列表。我們要想拿到token通過下標(biāo)訪問。
修改上述代碼:

import jsonpath

resp = response.json()  # 將返回值轉(zhuǎn)換成字典格式
token = jsonpath.jsonpath(resp, '$..token')  # token的jsonpath表達(dá)式:$..token
print(token[0])

執(zhí)行結(jié)果:

d653d78ac417f65e1cd38c6f3e220341

Jsonpath表達(dá)式解析的優(yōu)點(diǎn)如果響應(yīng)體缺少某個(gè)字段,通過Jsonpath表達(dá)式解析不到結(jié)果,就會(huì)返回False,永遠(yuǎn)不會(huì)發(fā)生異常。我們可根據(jù)返回結(jié)果進(jìn)行后續(xù)處理。

import jsonpath

resp = response.json()  # 將返回值轉(zhuǎn)換成字典格式
# 使用錯(cuò)誤的jsonpath表達(dá)式
token = jsonpath.jsonpath(resp, '$..token1')  # token的jsonpath表達(dá)式:$..token1
if isinstance(token, List):
    print(f'可以解析到token,值為:{token[0]}')
else:
    print(f'解析不到token,結(jié)果為:{token}')

# 使用正確的jsonpath表達(dá)式
token = jsonpath.jsonpath(resp, '$..token')  # token的jsonpath表達(dá)式:$..token
if isinstance(token, List):
    print(f'可以解析到token,值為:{token[0]}')
else:
    print(f'解析不到token,結(jié)果為:{token}')

執(zhí)行結(jié)果:

解析不到token,結(jié)果為:False
可以解析到token,值為:d653d78ac417f65e1cd38c6f3e220341

3、如何知道自己寫的jsonpath表達(dá)式是否正確呢?

jsonpath在線校驗(yàn)工具:http://jsonpath.com/
將response粘貼在Inputs區(qū)域,在JSONPath區(qū)域輸入表達(dá)式,在Evaluation Results區(qū)域查看是否解析到期望的值。當(dāng)解析不到值時(shí),返回的是空列表(No match)
Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果jsonpath表達(dá)式語法
Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果

九、獲取請(qǐng)求的信息

print(f'請(qǐng)求url:{response.request.url}')
print(f'請(qǐng)求方法:{response.request.method}')
print(f'請(qǐng)求Header:{response.request.headers}')
print(f'請(qǐng)求路徑:{response.request.path_url}')

執(zhí)行結(jié)果:

請(qǐng)求url:http://shop-xo.hctestedu.com/index.php?s=api/user/login&application=app&application_client_type=weixin
請(qǐng)求方法:POST
請(qǐng)求Header:{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '69', 'Content-Type': 'application/json'}
請(qǐng)求路徑:/index.php?s=api/user/login&application=app&application_client_type=weixin

十、json=data 和 data=data 參數(shù)區(qū)別

接口電商項(xiàng)目后臺(tái)代碼(PHP)中,json=data以及data=data這2種參數(shù)類型都可以接收。在實(shí)際項(xiàng)目應(yīng)用中,常見的報(bào)文格式是application/json。因此最常使用的是json=data

1、json=data

請(qǐng)求頭默認(rèn)為:Content-Type=application/json

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data, params=param_data)
# 查看請(qǐng)求中的請(qǐng)求頭信息,Content-Type=application/json
print(res.request.headers)
print(res.text)

執(zhí)行結(jié)果:

{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '69', 'Content-Type': 'application/json'}
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}

2、data=data

請(qǐng)求頭默認(rèn)為:application/x-www-form-urlencoded

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, data=data, params=param_data)
# 查看請(qǐng)求中的請(qǐng)求頭信息,Content-Type=application/x-www-form-urlencoded
print(res.request.headers)
print(res.text)

執(zhí)行結(jié)果:

{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '50', 'Content-Type': 'application/x-www-form-urlencoded'}
{"msg":"登錄成功","code":0,"data":{"id":"22299","username":"xxxxx","nickname":"","mobile":"","email":"","avatar":"http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg","alipay_openid":"","weixin_openid":"","weixin_unionid":"","weixin_web_openid":"","baidu_openid":"","toutiao_openid":"","qq_openid":"","qq_unionid":"","integral":"0","locking_integral":"0","referrer":"0","add_time":"1678005098","add_time_text":"2023-03-05 16:31:38","mobile_security":"","email_security":"","user_name_view":"xxxxx","is_mandatory_bind_mobile":0,"token":"d653d78ac417f65e1cd38c6f3e220341"}}

3、設(shè)置請(qǐng)求頭

如果是java項(xiàng)目,spring會(huì)將請(qǐng)求實(shí)體的內(nèi)容自動(dòng)轉(zhuǎn)換為Bean,但前提是請(qǐng)求的Content-Type必須設(shè)置為application/json

在請(qǐng)求頭中定義發(fā)送報(bào)文的格式

1、Content-Type: application/json

headers = {
    'Content-Type': 'application/json'
    # 'Content-Type': 'application/x-www-form-urlencoded'
}
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, params=param_data, json=data, headers=headers)

print(res.request.headers)

執(zhí)行結(jié)果:

{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '50'}

2、Content-Type:application/x-www-form-urlencoded

headers = {
    # 'Content-Type': 'application/json'
    'Content-Type': 'application/x-www-form-urlencoded'
}
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, params=param_data, data=data, headers=headers)

print(res.request.headers)

執(zhí)行結(jié)果:

{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': '69'}

十一、Json和字典數(shù)據(jù)轉(zhuǎn)換

1、json.dumps(),將字典轉(zhuǎn)換成Json

使用json.dumps()可以將字典轉(zhuǎn)換成Json

test = {
    "msg": "登錄成功",
    "code": 0,
    "data": {
        "id": "22299",
        "username": "Summer",
        "nickname": "",
        "mobile": "",
        "email": "",
        "avatar": "http:\/\/shop-xo.hctestedu.com\/static\/index\/default\/images\/default-user-avatar.jpg",
        "alipay_openid": "",
        "weixin_openid": "",
        "weixin_unionid": "",
        "weixin_web_openid": "",
        "baidu_openid": "",
        "toutiao_openid": "",
        "qq_openid": "",
        "qq_unionid": "",
        "integral": "0",
        "locking_integral": "0",
        "referrer": "0",
        "add_time": "1678005098",
        "add_time_text": "2023-03-05 16:31:38",
        "mobile_security": "",
        "email_security": "",
        "user_name_view": "chengcheng",
        "is_mandatory_bind_mobile": 0,
        "token": "d653d78ac417f65e1cd38c6f3e220341"
    }
}

print(type(test))
print(json.dumps(test))
print(type(json.dumps(test)))

執(zhí)行結(jié)果:

<class 'dict'>
{"msg": "\u767b\u5f55\u6210\u529f", "code": 0, "data": {"id": "22299", "username": "Summer", "nickname": "", "mobile": "", "email": "", "avatar": "http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg", "alipay_openid": "", "weixin_openid": "", "weixin_unionid": "", "weixin_web_openid": "", "baidu_openid": "", "toutiao_openid": "", "qq_openid": "", "qq_unionid": "", "integral": "0", "locking_integral": "0", "referrer": "0", "add_time": "1678005098", "add_time_text": "2023-03-05 16:31:38", "mobile_security": "", "email_security": "", "user_name_view": "chengcheng", "is_mandatory_bind_mobile": 0, "token": "d653d78ac417f65e1cd38c6f3e220341"}}
<class 'str'>

2、json.loads(),將Json轉(zhuǎn)換成字典

使用json.loads()可以將Json轉(zhuǎn)換成字典

print(json.loads(json.dumps(test)))
print(type(json.loads(json.dumps(test))))

執(zhí)行結(jié)果:

{'msg': '登錄成功', 'code': 0, 'data': {'id': '22299', 'username': 'Summer', 'nickname': '', 'mobile': '', 'email': '', 'avatar': 'http:\\/\\/shop-xo.hctestedu.com\\/static\\/index\\/default\\/images\\/default-user-avatar.jpg', 'alipay_openid': '', 'weixin_openid': '', 'weixin_unionid': '', 'weixin_web_openid': '', 'baidu_openid': '', 'toutiao_openid': '', 'qq_openid': '', 'qq_unionid': '', 'integral': '0', 'locking_integral': '0', 'referrer': '0', 'add_time': '1678005098', 'add_time_text': '2023-03-05 16:31:38', 'mobile_security': '', 'email_security': '', 'user_name_view': 'chengcheng', 'is_mandatory_bind_mobile': 0, 'token': 'd653d78ac417f65e1cd38c6f3e220341'}}
<class 'dict'>

3、json格式報(bào)文發(fā)送

方法一:參數(shù)是data,值:將字典data轉(zhuǎn)換成json

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
headers = {
    'Content-Type': 'application/json'
}
res = requests.post(url=url, data=json.dumps(data), headers=headers)
print(res.text)

方法二:參數(shù)是json,值:字典data

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data)
print(res.text)

print(res.json())
print(type(res.json()))
assert "登錄成功" == res.json()['msg']

十二、獲取接口響應(yīng)時(shí)間

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'
res = requests.post(url=url, json=data)
print(res.text)
# 獲取接口響應(yīng)時(shí)間,單位秒
print(r.elapsed.total_seconds())

執(zhí)行結(jié)果:

{"msg":"登錄成功","code":0,"data":{"body_html":""}}
0.078264

十三、接口調(diào)用失敗處理

同一個(gè)用例中有多個(gè)接口調(diào)用,一個(gè)接口調(diào)用失敗如何防止程序終止?
用于判斷接口請(qǐng)求的狀態(tài)碼是否為200,如果是,則返回none,如果不是則返回異常。
調(diào)用接口時(shí)結(jié)合try…except進(jìn)行使用。

# 模擬接口404,使用不存在的request url: login1
url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login1'
res = requests.post(url=url, json=data)

try:
    assert 200 == res.status_code
except:
    # 異常處理1:直接跳過,可繼續(xù)執(zhí)行后面代碼
    # pass
    # 異常處理2:打印詳細(xì)異常信息
    print(res.status_code)
    res.raise_for_status()
else:
    print(res.text)

執(zhí)行結(jié)果:

404
Traceback (most recent call last):
  File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 220, in <module>
    assert 200 == res.status_code
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Coding\python-workspace\Interface_test\first_requests.py", line 226, in <module>
    res.raise_for_status()
  File "D:\Developer\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://shop-xo.hctestedu.com/index.php?s=api/user/login1

十四、接口超時(shí)

url = 'http://shop-xo.hctestedu.com/index.php?s=api/user/login'

try:
    res = requests.post(url=url, json=data, timeout=0.01)  # timeout,單位秒
except (TimeoutError, ReadTimeout, ConnectTimeout):
    # ConnectTimeout:指的是建立連接所用的時(shí)間,適用于網(wǎng)絡(luò)狀況正常的情況下,兩端連接所用的時(shí)間。
    # ReadTimeout:指的是建立連接后從服務(wù)器讀取到可用資源所用的時(shí)間。
    print("發(fā)生錯(cuò)誤,請(qǐng)稍后重試")
else:
    # 獲取接口響應(yīng)時(shí)間,單位秒
    print(res.elapsed.total_seconds())
    print(res.text)

執(zhí)行結(jié)果:

發(fā)生錯(cuò)誤,請(qǐng)稍后重試

當(dāng)把timeout改成0.1,執(zhí)行結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-423558.html

0.07419
{"msg":"登錄成功","code":0,"data":{"body_html":""}}

到了這里,關(guān)于Python發(fā)送Post請(qǐng)求及解析響應(yīng)結(jié)果的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【從零學(xué)習(xí)python 】92.使用Python的requests庫(kù)發(fā)送HTTP請(qǐng)求和處理響應(yīng)

    URL參數(shù)傳遞方式一:使用字典傳遞參數(shù) 這段代碼使用 requests 庫(kù)發(fā)送了一個(gè)GET請(qǐng)求,指定了一個(gè)URL( \\\'https://www.apiopen.top/satinApi\\\' )和一個(gè)參數(shù)字典( params )。 params 字典中包含了請(qǐng)求的參數(shù),其中 type 的值為1, page 的值為2。 requests.get() 方法會(huì)自動(dòng)將參數(shù)拼接到URL中,并發(fā)送GET請(qǐng)求

    2024年02月11日
    瀏覽(28)
  • python 發(fā)送和接收post請(qǐng)求

    bottle是python的web框架,只需要引用一個(gè) .py 文件即可,點(diǎn)擊去下載頁

    2024年02月15日
    瀏覽(15)
  • Python+Requests模擬發(fā)送post請(qǐng)求

    Python+Requests模擬發(fā)送post請(qǐng)求

    發(fā)送post請(qǐng)求的基礎(chǔ)知識(shí)dumps和loads 代碼示例: 以微信開放平臺(tái)舉例 發(fā)送post請(qǐng)求 查看執(zhí)行結(jié)果: ?上傳文件 查看執(zhí)行結(jié)果 ?封裝post請(qǐng)求 代碼示例: 封裝main方法 代碼示例: 封裝測(cè)試類 示例代碼: 光學(xué)理論是沒用的,要學(xué)會(huì)跟著一起敲,要?jiǎng)邮謱?shí)操,才能將自己的所學(xué)運(yùn)用

    2024年02月07日
    瀏覽(22)
  • 使用hutool發(fā)送POST請(qǐng)求

    使用hutool發(fā)送POST請(qǐng)求

    之前使用Java程序發(fā)送請(qǐng)求都是使用的HttpURLConnection,不太方便,可以使用hutool封裝好的方法。 返回結(jié)果包括響應(yīng)頭和響應(yīng)體兩部分,其中響應(yīng)體是后端通過@ResponseBody返回的數(shù)據(jù);響應(yīng)頭包含一些其他信息,比如cookie。 hutool參考文檔

    2024年02月11日
    瀏覽(27)
  • 使用Postman發(fā)送GET請(qǐng)求和POST請(qǐng)求

    使用Postman發(fā)送GET請(qǐng)求和POST請(qǐng)求

    Postman是一款流行的API測(cè)試和開發(fā)工具,它提供了一個(gè)易于使用的界面,用于發(fā)送HTTP請(qǐng)求并與REST、SOAP和其他Web服務(wù)進(jìn)行交互。以下是對(duì)Postman的簡(jiǎn)單介紹: 發(fā)送HTTP請(qǐng)求:Postman允許您以簡(jiǎn)單直觀的方式發(fā)送各種類型的HTTP請(qǐng)求(GET、POST、PUT、DELETE等)到指定的URL。您可以設(shè)置請(qǐng)

    2024年02月05日
    瀏覽(38)
  • 使用HttpURLConnection發(fā)送POST請(qǐng)求并攜帶請(qǐng)求參數(shù)

    這里的param是請(qǐng)求參數(shù),需要將其轉(zhuǎn)換為字節(jié)數(shù)組后寫入輸出流。 這里的response是響應(yīng)數(shù)據(jù),需要將其讀取為字符串后使用。 完整的示例代碼如下所示: 需要注意的是,以上示例代碼中的請(qǐng)求參數(shù)是以字符串形式傳遞的,如果需要傳遞復(fù)雜的請(qǐng)求參數(shù),可以考慮使用JSON等格

    2024年02月04日
    瀏覽(26)
  • 使用hutool工具發(fā)送post請(qǐng)求

    ?import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; ? ? ? ? JSONObject jsonObject = JSONUtil.createObj(); ? ? ? ? ? ? jsonObject.put(\\\"shift\\\", \\\"D\\\"); ? ? ? ? ? ? jsonObject.put(\\\"model\\\", dataMap.get(\\\"MODEL\\\")); ? ? ? ? ? ? jsonObject.put(\\\"stage\\\", dataMap.

    2024年02月13日
    瀏覽(22)
  • Python爬蟲requests判斷請(qǐng)求超時(shí)并重新post/get發(fā)送請(qǐng)求

    在上面的示例中,send_request_get函數(shù)接受一個(gè)URL作為參數(shù),并可選地指定最大重試次數(shù)和超時(shí)時(shí)間。函數(shù)使用 requests.get 發(fā)送GET請(qǐng)求,并設(shè)置了超時(shí)時(shí)間為5秒。如果請(qǐng)求超時(shí),會(huì)捕獲 requests.exceptions.Timeout 異常,并輸出重試信息。如果發(fā)生其他異常,會(huì)捕獲 requests.exceptions.Req

    2024年02月11日
    瀏覽(34)
  • 使用Go發(fā)送HTTP POST請(qǐng)求

    使用Go發(fā)送HTTP POST請(qǐng)求

    在Go語言中,我們可以使用 net/http 包來發(fā)送HTTP POST請(qǐng)求。以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用Go發(fā)送HTTP POST請(qǐng)求并獲取響應(yīng)。 go 復(fù)制代碼 package ?main import ?( \\\"bytes\\\" ? \\\"fmt\\\" ? \\\"io/ioutil\\\" ? \\\"net/http\\\" ? ) func ? main () ?{ // 創(chuàng)建一個(gè)HTTP客戶端 client := http.Client{} // 創(chuàng)建一個(gè)POST請(qǐng)求

    2024年01月23日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包