java如何用soap
使用 Java 调用 SOAP 服务
Java 提供了多种方式调用 SOAP Web 服务,以下是几种常见方法:
使用 JAX-WS 生成客户端代码
JDK 自带的 wsimport 工具可以根据 WSDL 文件生成客户端代码:
wsimport -keep http://example.com/service?wsdl
生成的代码包含服务接口和存根类,可以直接在 Java 代码中调用:
MyService service = new MyService();
MyServicePortType port = service.getMyServicePort();
String result = port.myOperation("param");
动态调用 SOAP 服务
如果不希望生成客户端代码,可以使用动态调用方式:
URL wsdlURL = new URL("http://example.com/service?wsdl");
QName serviceName = new QName("http://example.com", "MyService");
Service service = Service.create(wsdlURL, serviceName);
QName portName = new QName("http://example.com", "MyServicePort");
MyServicePortType port = service.getPort(portName, MyServicePortType.class);
String result = port.myOperation("param");
使用 Apache CXF
Apache CXF 是一个流行的 Web 服务框架,可以简化 SOAP 调用:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(MyServicePortType.class);
factory.setAddress("http://example.com/service");
MyServicePortType client = (MyServicePortType) factory.create();
String result = client.myOperation("param");
使用 Spring Web Services
在 Spring 项目中可以使用 Spring-WS 调用 SOAP 服务:
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setDefaultUri("http://example.com/service");
MyRequest request = new MyRequest();
request.setParam("param");
MyResponse response = (MyResponse) webServiceTemplate.marshalSendAndReceive(request);
手动构建 SOAP 消息
对于需要更精细控制的情况,可以手动构建 SOAP 消息:
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();
SOAPElement operation = body.addChildElement("myOperation", "ns");
operation.addChildElement("param").addTextNode("value");
URL endpoint = new URL("http://example.com/service");
SOAPMessage response = connection.call(message, endpoint);
处理 SOAP 安全
如果服务需要 WS-Security 认证,可以使用 WSS4J:
Map<String, Object> props = new HashMap<>();
props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
props.put(WSHandlerConstants.USER, "username");
props.put(WSHandlerConstants.PASSWORD, "password");
props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(props);
client.getOutInterceptors().add(wssOut);
处理 SOAP 附件
对于包含附件的 SOAP 消息:

AttachmentPart attachment = message.createAttachmentPart();
attachment.setContent(new FileDataSource("file.txt"));
attachment.setContentType("text/plain");
message.addAttachmentPart(attachment);
以上方法涵盖了 Java 调用 SOAP 服务的主要场景,开发者可以根据项目需求选择合适的方式。






