python接口自动化26-发xml格式post请求
前言
post请求相对于get请求多一个body部分,body部分常见的数据类型有以下四种(注意是常见的,并不是只有4种)
application/x-www-form-urlencoded
application/json
text/xml
multipart/form-data
本篇讲xml这种类型的body案例,如何用python去实现
text/xml
1.首先要确定post请求的body部分类型是xml格式,可以用fiddler抓包工具,抓到请求后点开raw。看到body部分格式如下
<?xml version=“1.0” encoding = “UTF-8”?> <COM> <REQ name="上海-悠悠"> <USER_ID>yoyoketang</USER_ID> <COMMODITY_ID>123456</COMMODITY_ID> <SESSION_ID>absbnmasbnfmasbm1213</SESSION_ID> </REQ> </COM>
使用fiddler模拟
1.先不着急去写python代码,先在工具上请求一次,看能不能请求成功,点开fiddler工具上composer菜单
2.将xml数据直接复制到右下方Request Body部分,然后点右上角Execute就能执行了
python实现
1.xml格式的body部分直接写成一个字符串类型就行了,遇到换行的字符串,在后面加个反斜杠
2.body参数用data去接收传入,要是遇到编码问题报错,就对body部分encode下再传入
# coding:utf-8 import requests
# 作者:上海-悠悠 QQ交流群:588402570
url = "http://httpbin.org/post" # python3字符串换行,在右边加个反斜杠 body = '<?xml version="1.0" encoding = "UTF-8"?>' '<COM>' '<REQ name="上海-悠悠">' '<USER_ID>yoyoketang</USER_ID>' '<COMMODITY_ID>123456</COMMODITY_ID>' '<SESSION_ID>absbnmasbnfmasbm1213</SESSION_ID>' '</REQ>' '</COM>' # 遇到编码报错时候,对body进行encode r = requests.post(url, data=body.encode("utf-8")) print(r.text)
3.运行结果
{"args":{},"data":"<?xml version=\"1.0\" encoding = \"UTF-8\"?><COM><REQ name=\"\u4e0a\u6d77-\u60a0\u60a0\"><USER_ID>yoyoketang</USER_ID><COMMODITY_ID>123456</COMMODITY_ID><SESSION_ID>absbnmasbnfmasbm1213</SESSION_ID></REQ></COM>","files":{},"form":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"192","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"116.228.224.250","url":"http://httpbin.org/post"}
读xml数据
1.xml格式的数据写到代码里面,不太直观,后期维护也不方便,可以把xml格式数据单独拿出来写到一个文件里,再用open函数去读取
2.新建一个body1_xml文件,写入内容如下:
<?xml version="1.0" encoding = "UTF-8"?> <COM> <REQ name="上海-悠悠"> <USER_ID>yoyoketang</USER_ID> <COMMODITY_ID>123456</COMMODITY_ID> <SESSION_ID>absbnmasbnfmasbm1213</SESSION_ID> </REQ> </COM>
3.用open函数去读xml内容
# coding:utf-8 import os # 作者:上海-悠悠 QQ交流群:588402570
curpath = os.path.dirname(os.path.realpath(__file__)) xmlpath = os.path.join(curpath, "body1_xml") with open(xmlpath, encoding="utf-8") as fp: body = fp.read() # 读取xml文件 print(body)
3.参考代码:
# coding:utf-8 import requests
# 作者:上海-悠悠 QQ交流群:588402570 url = "http://httpbin.org/post" # xml格式body with open("body1_xml", encoding="utf-8") as fp: body = fp.read() print(body) # 遇到编码报错时候,对body进行encode r = requests.post(url, data=body.encode("utf-8")) print(r.text)