Java调用WebService接口的SOAP方式

Java调用WebService接口的SOAP方式:

import javax.xml.soap.*;
import java.io.ByteArrayOutputStream;

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();

            // 创建SOAP信封
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
            
                  
        soapEnvelope.addNamespaceDeclaration("web","http://www.userDemo.com/webservice");

            // 创建SOAP主体
            SOAPBody soapBody = soapEnvelope.getBody();

            // 创建SOAP操作
            SOAPElement soapOperation = soapBody.addChildElement("getUser", "web");
            SOAPElement soapArgument = soapOperation.addChildElement("user");
            soapArgument.addTextNode("cxzm");

            // 发送SOAP消息并获取响应
            String endpointUrl = "http://www.example.com/webservice";
            SOAPMessage soapResponse = soapConnection.call(soapMessage, endpointUrl);

            // 处理SOAP响应
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            soapResponse.writeTo(outputStream);
            String responseString = outputStream.toString();

            // 输出SOAP响应
            System.out.println("SOAP响应:"+responseString);

            // 关闭SOAP连接
            soapConnection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(WebService)