天天看點

Python+requests庫發送接口入參為xml格式的接口請求【多測師】

Python+requests庫發送接口入參為xml格式的接口請求

一)接口入參準備:

url位址:http://httpbin.org/post

入參:

<?xml version="1.0" encoding = "UTF-8"?>
<COM>
    <REQ name="多測師_王sir">
        <USER_ID>duoceshi</USER_ID>
        <COMMODITY_ID>123456</COMMODITY_ID>
        <SESSION_ID>DwO68dQFBg9xIizKsC6RhaeHRxqIT9nmU</SESSION_ID>
    </REQ>
</COM>      

二)把上面入參内容儲存放入到duoceshi.xml檔案中:

Python+requests庫發送接口入參為xml格式的接口請求【多測師】

三)發送接口請求:

#coding=utf-8
'''
python處理xml格式入參的接口
'''

#1.先把xml入參用open函數讀出來變為字元串
def read_xml():
    '''
    讀取xml檔案
    :return:
    '''
    f = open('duoceshi.xml',"r")
    body = f.read()
    #print(body)
    return body

#2.發送接口請求
import requests

class Api_Test(object):

    def send_post(self):
        url = "http://httpbin.org/post"
        r = requests.post(url, data=read_xml())
        print(r.text)

if __name__ == '__main__':
    api = Api_Test()  #建立對象
    api.send_post()   #調用執行個體方法      

四)檢視響應體的内容:

{
  "args": {}, 
  "data": "<?xml version=\"1.0\" encoding = \"UTF-8\"?>\n
       <COM>\n    
          <REQ name=\"\u591a\u6d4b\u5e08_\u738bsir\">\n        
         <USER_ID>duoceshi</USER_ID>\n        
         <COMMODITY_ID>123456</COMMODITY_ID>\n        
         <SESSION_ID>DwO68dQFBg9xIizKsC6RhaeHRxqIT9nmU</SESSION_ID>\n    
         </REQ>\n
       </COM>\n\n\n", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "248", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-5eb7ea8e-2b31c719d1ecd8f197e39c12"
  }, 
  "json": null, 
  "origin": "222.65.223.177", 
  "url": "http://httpbin.org/post"
}      

繼續閱讀