最近接觸到一個post請求,發送報文是 以xml格式的。如下:
准備用Python + Requests庫來進行接口的代碼自動化。 記錄下 過程。
首先,postman請求,用fidder抓包,確定下請求報文:
看下請求報文具體。復制下,使用fiddler的 composer ,請求方式post,請求地址輸入,下面Request Body 中粘貼復制的請求報文,點擊execute,執行。執行成功,成功返回報文
2. 使用python代碼
xml 格式的直接放置body,字符串承接,每一行最后增加\換行符,requests 的post請求,用data 來接。進行請求。即可請求成功。
(如果失敗,post請求data的body進行一下utf-8轉換。 re = requests.post(url=url,data=body.encoding("utf-8")) )
代碼如下:
url = "http://xx.xx.xx.xxx:xxxxx/xxxxxx/Cmis2YcloansHttpChannel"
body = 'XXXXX;calculateService;'\
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'\
'<msgbody>'\
'<reqId>reqID</reqId>'\
'<reqTime>2019-08-19 17:16:15.123</reqTime>'\
'<serviceId>calculateService</serviceId>'\
'<channelId>YouZan</channelId>'\
'<subChannelId></subChannelId>'\
'<source></source>'\
'<ip>127.0.0.1</ip>'\
'<version></version>'\
'<BCH_CDE>branch_code</BCH_CDE>'\
'<loanNo>50000320120198253002</loanNo>'\
'<setlValDt>2020-12-08</setlValDt>'\
'<actvPayAmt>45.22</actvPayAmt>'\
'<trialDt>2020-12-08</trialDt>'\
'<paymMode>AT</paymMode>'\
'</msgbody>'\
re = requests.post(url=url,data=body)
print(re.text)
再當前文件中請求成功。
3.xml報文放置xml文件中,讀取xml文件
一般請求報文放置 XML 文件中,pycharm 中新增xml 文件。文件中將xml請求報文放置。如下:
當前請求中,使用Open函數讀取xml文件內容,請求代碼
參考代碼:
url = "http://xx.xx.xx.xxx:xxxxx/xxxxxx/Cmis2YcloansHttpChannel"
headers = {'Content-Type':'application/xml'}
with open('youzanLoanTrial.xml',encoding='utf-8') as fp:
body1 = fp.read()
re = requests.post(url=url,headers=headers,data=body1)
print(re.text)
代碼成功運行,運行結果如下:
這是request請求,第四種比較常用的請求方式。
{'Content-Type': 'application/json'},
{'Content-Type': 'application/x-www-form-urlencoded'}
{'Content-Type':'multipart/form-data}
{'Content-Type':'text/xml}
Requests庫post請求,四種常用請求方式:application/json,application/form,multipart/form-data,text/xml