在Java中發送SOAP請求有多種方法,其中一種常用的方法是使用JAX-WS(Java API for XML Web Services)。
下面是一個簡單的示例代碼,演示如何使用JAX-WS發送SOAP請求:
import javax.xml.soap.*;
public class SoapClient {
public static void main(String[] args) {
try {
// 創建SOAP連接
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// 創建SOAP消息
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
// 創建SOAP消息的部分
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
// 添加SOAP消息體內容
soapBody.addBodyElement(soapEnvelope.createName("HelloWorld", "ns", "http://www.example.org"));
// 設置SOAP地址
String url = "http://localhost:8080/HelloWorldService";
SOAPMessage response = soapConnection.call(soapMessage, url);
// 處理SOAP響應
SOAPBody responseBody = response.getSOAPBody();
System.out.println("Response: " + responseBody.getTextContent());
// 關閉SOAP連接
soapConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們首先創建了一個SOAP連接,然后創建了一個SOAP消息,并設置了SOAP消息體內容。接著我們指定了SOAP服務器的地址,最后發送SOAP請求并處理響應。
請注意,以上示例是一個簡單的演示,實際項目中可能需要更復雜的SOAP消息結構和處理邏輯。您可以根據具體需求進行調整和擴展。