跳到主要內容

Java make SOAP call

參考文章
https://docs.oracle.com/cd/E19879-01/819-3669/bnbhw/index.html

SOAP的定義請參考wiki
雖然目前已經是過時的資料交換技術
不過像是在台灣只會 Microsoft (舊)技術的廠商還是不少
有時候還是只能跟著用這些方式配合

這次 sample code 的github連結
會寫這篇是因為Java的SOAP相關的 library 體積都滿龐大的
不過若工作上用不到太複雜的設定,靠 Java 本身的支援也能避免 library 的依賴及帶來的麻煩
因為跟SOAP搭配的回傳資訊大多是XML格式,所以下面的code示範將結果當成XML的處理方式

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import java.io.IOException;
import java.io.StringReader;

SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://[SOAP_SERVER_IP]/[SOMESERVVICE]/[SERVICE_NAME].asmx?WSDL",
            serverURI = "http://tempuri.org/";

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    QName bodyName = new QName(serverURI, "Service Name");
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    QName name = new QName("Node Name");
    SOAPElement symbol = bodyElement.addChildElement(name);
    symbol.addTextNode("Node Value");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "Service Name");

    // Process the SOAP Response
    SOAPMessage soapResponse = soapConnection.call(soapMessage, url);
    SOAPBody body = soapResponse.getSOAPBody();
    String resText = body.getTextContent();
    soapConnection.close();

SAXBuilder builder = new SAXBuilder();
try {
    Document doc = builder.build(new InputSource(new StringReader(resText)));
    Element _xml = doc.getRootElement();
    if (!"[xml name]".equals(_xml.getName())) return;
    String returnCode = _xml.getChild("ReturnCode").getText();
    ....
} catch (Exception e) {
    System.out.print(e);
}


淡紅色文字請自行嘗試並替換成適用於自己服務的設定
這段code雖然沒有到極短,但是能夠處理簡單的SOAP需求了
用來替代肥大的 library 已經有足夠的好處了
當然如果合作夥伴都用更新、更合適得技術會更好

留言