萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 呼叫 Java Web Service (WSDL) 發送簡訊:SOAP 封包組裝與 MSXML 發送實戰

對方提供的 WSDL 關鍵資訊

  • 服務位址:https://10.13.255.196/SmsDownlinkReceive/services/DownlinkServiceImpl
  • 目標命名空間:https://service.downlink.sms.mdcl.com
  • 操作:sendSms (參數:userName, password, importance, mobile, smsBody, allowStartTime, allowEndTime, deadLineTime, appointTime, smsType)
  • SOAP 版本:1.1 (HTTP Content-Type: text/xml; charset=utf-8)

ASP 組裝 SOAP 請求並發送

<%
Function SendSmsViaJavaWS(mobile, content, userName, password)
  Dim soapBody, soapEnv, xhr, url, ns, action
  url = "https://10.13.255.196/SmsDownlinkReceive/services/DownlinkServiceImpl"
  ns = "https://service.downlink.sms.mdcl.com"
  action = "sendSms" ' SOAPAction 通常為操作名或 namespace#operation

  ' 組裝 SOAP Body (依 WSDL 定義順序)
  soapBody = "" & _
    "" & EscapeXML(userName) & "" & _
    "" & EscapeXML(password) & "" & _
    "1" & _
    "" & EscapeXML(mobile) & "" & _
    "" & EscapeXML(content) & "" & _
    "0" & _
    "2400" & _
    "" & _
    "" & _
    "1" & _
    ""

  soapEnv = "" & _
    "" & _
    "" & soapBody & "" & _
    ""

  Set xhr = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
  xhr.SetOption 2, 13056 ' SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS (若測試環境無效憑證)
  xhr.Open "POST", url, False
  xhr.SetRequestHeader "Content-Type", "text/xml; charset=utf-8"
  xhr.SetRequestHeader "SOAPAction", """" & ns & "#" & action & """"
  xhr.Send soapEnv

  If xhr.Status = 200 Then
    ' 解析回應
    Dim xmlDoc, node
    Set xmlDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
    xmlDoc.async = False
    xmlDoc.LoadXML xhr.ResponseText
    Set node = xmlDoc.SelectSingleNode("//*[local-name()='sendSmsReturn']")
    If Not node Is Nothing Then
      SendSmsViaJavaWS = node.Text ' 回傳結果字串 (視 WSDL 定義)
    Else
      SendSmsViaJavaWS = "UNKNOWN_RESPONSE: " & xhr.ResponseText
    End If
  Else
    SendSmsViaJavaWS = "HTTP_ERROR: " & xhr.Status & " " & xhr.StatusText
  End If
End Function

Function EscapeXML(str)
  str = Replace(str, "&", "&")
  str = Replace(str, "<", "<")
  str = Replace(str, ">", ">")
  str = Replace(str, """", """)
  str = Replace(str, "'", "'")
  EscapeXML = str
End Function
%>

呼叫範例

<%
Dim result
result = SendSmsViaJavaWS("0912345678", "測試簡訊內容", "api_user", "api_pass")
Response.Write "發送結果: " & result
%>

常見問題排查

現象可能原因解決
HTTP 200 但無回傳值 / 空白SOAPAction 錯誤、命名空間不符、參數順序/型別錯誤用 SoapUI 匯入 WSDL 測試成功後,抓取 Raw Request 複製到 ASP
HTTP 500 / Fault驗證失敗、參數驗證不通 (手機號格式、長度、時間格式)檢查 WSDL 中 xsd:pattern, minLength 等限制
憑證錯誤 (HTTPS)伺服器憑證不受信xhr.SetOption 2, 13056 忽略憑證錯誤 (僅測試環境),生產環境必須匯入根憑證
中文亂碼編碼不一致確保 ASP 頁面 Response.Charset = "UTF-8"、SOAP 宣告 encoding="utf-8"、DB/變數皆 UTF-8

進階:使用 WSE / WCF 產生 Proxy 類別 (若環境允許 .NET)

若伺服器已安裝 .NET Framework,可用 wsdl.exe 或 Visual Studio 「加入 Web 參考」產生強型別 Proxy,再編譯為 COM Visible DLL (regasm /codebase /tlb SmsProxy.dll),ASP 直接 CreateObject("SmsProxy.Sender") 呼叫,避免手工組 XML。

copyright © 萬盛學電腦網 all rights reserved