python通過http請求發送soap報文進行webservice接口調用


最近學習Python調用webservice 接口,開始的時候主要采用suds 的方式生產client調用,后來發現公司的短信接口采用的是soap報文來調用的,然后開始了谷歌,最后采用httplib 模塊發送報文數據,來調用接口,下面直接來一個實例

# -*- coding: utf-8 -*-
import httplib


def mdsmssend(sn,pwd,mobile,context):
  #定義發送報文
   SoapMessage ='''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <mdsmssend xmlns="http://entinfo.cn/">
      <sn>%s</sn>
      <pwd>%s</pwd>
      <mobile>%s</mobile>
      <content>%s</content>
    </mdsmssend>
  </soap:Body>
</soap:Envelope>'''

   SoapMessage=SoapMessage %(sn,pwd,mobile,context)
   #使用的WebService地址為sdk.entinfo.cn:8061/webservice.asmx,
   webservice = httplib.HTTP("sdk.entinfo.cn:8061")
   #連接到服務器后的第一個調用。它發送由request字符串到到服務器
   webservice.putrequest("POST", "/webservice.asmx")
   webservice.putheader("Host", "sdk.entinfo.cn:8061")
   webservice.putheader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)")
   webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
   webservice.putheader("Content-length", "%d" % len(SoapMessage))
   webservice.putheader("SOAPAction", "\"http://entinfo.cn/mdsmssend\"")
   #發送空行到服務器,指示header的結束
   webservice.endheaders()
   #發送報文數據到服務器
   webservice.send(SoapMessage)
   #獲取返回HTTP 響應信息
   statuscode, statusmessage, header = webservice.getreply()
   return statuscode

這樣大功告成


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM