SOAP JAVA实例

本文档介绍了Java调用SOAP Web Service的简单应用。

一、SOAP

SOAP(Simple Object Access Protocol)是一种交换数据的协议规范,特点是轻量级、基于XML。

请求和响应都是xml的形式,示例如下:

  • request

POST /regcodeService.asmx HTTP/1.1
Host: weixin.fscut.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "https://weixin.fscut.com/MakeRegCode"
​
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <SessionHeader xmlns="https://weixin.fscut.com">
      <LangID>int</LangID>
      <SvcVersion>int</SvcVersion>
      <OEMCode>int</OEMCode>
      <SessionID>string</SessionID>
      <OperFrom>string</OperFrom>
    </SessionHeader>
  </soap:Header>
  <soap:Body>
    <MakeRegCode xmlns="https://weixin.fscut.com">
      <Serial>string</Serial>
      <ExpireDate>string</ExpireDate>
      <Flags>int</Flags>
      <CustomName>string</CustomName>
      <Mobile>string</Mobile>
      <Comment>string</Comment>
    </MakeRegCode>
  </soap:Body>
</soap:Envelope>
  • response

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
​
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <MakeRegCodeResponse xmlns="https://weixin.fscut.com">
      <MakeRegCodeResult>
        <Status>int</Status>
        <ErrMsg>string</ErrMsg>
        <Data>string</Data>
      </MakeRegCodeResult>
    </MakeRegCodeResponse>
  </soap:Body>
</soap:Envelope>

由示例可以看出,一条SOAP消息就是一个XML文档,一般包含以下元素:

  • Envelope,标识此XML是一条SOAP消息

  • Header,头部信息

  • Body,调用和响应信息

  • Fault,处理消息时发生的错误信息

按照处理XML的方式读写即可。

二、在Java中应用

参考:

How to do a SOAP Web Service call from Java class

首先要创建客户端发起请求,与URL请求类似,步骤如下:

  • 创建连接

  • 设置MimeHeaders

  • 设置参数(soapHeader + soapBody)

  • 解析response

import javax.xml.soap.*;
​
public class SOAPClientSAAJ {
​
    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
​
​
            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action
​
            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
        String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
​
        callSoapWebService(soapEndpointUrl, soapAction);
    }
​
    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();
​
        String myNamespace = "myNamespace";
        String myNamespaceURI = "https://www.w3schools.com/xml/";
​
        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
​
            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:CelsiusToFahrenheit>
                        <myNamespace:Celsius>100</myNamespace:Celsius>
                    </myNamespace:CelsiusToFahrenheit>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */
​
        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
        soapBodyElem1.addTextNode("100");
    }
​
    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
​
            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
​
            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();
​
            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }
​
    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
​
        createSoapEnvelope(soapMessage);
​
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);
​
        soapMessage.saveChanges();
​
        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");
​
        return soapMessage;
    }
​
}

除此之外,设置session header的实例如下

SOAPHeader header = soapMessage.getSOAPHeader();
SOAPHeaderElement headerElement = header.addHeaderElement(new QName(SOAP_NAMESPACE_URI,
        SOAP_KEY_SESSION_HEADER));
SOAPElement langElement = headerElement.addChildElement(SOAP_KEY_LANG_ID);
langElement.addTextNode(SOAP_VALUE_LANG_ID);

response的结果和request类似,可通过解析soapBody的方式获得结果。

处理方式与处理XML类似,不再赘述。

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java CXF 是一个开源的 Web 服务框架,它提供了一种简单的方式来构建和发布 Web 服务。CXF 支持多种 Web 服务标准,例如 SOAP、REST、XML/JSON 等。CXF 提供了丰富的功能,包括数据绑定、安全性、日志记录、异常处理等。 以下是一些 CXF 高级功能的实例: 1. 自定义 Binding Provider CXF 提供了多种默认的 Binding Provider,但是如果需要自定义 Binding Provider,可以通过实现 org.apache.cxf.binding.BindingFactory 接口来完成。下面是一个自定义 Binding Provider 的示例: ```java public class CustomBindingFactory implements BindingFactory { private Map<String, BindingFactory> bindingMap = new HashMap<>(); @Override public Binding createBinding(BindingInfo bindingInfo) { String bindingId = bindingInfo.getBindingId(); if (bindingMap.containsKey(bindingId)) { return bindingMap.get(bindingId).createBinding(bindingInfo); } throw new RuntimeException("Unsupported binding: " + bindingId); } public void addBinding(String bindingId, BindingFactory bindingFactory) { bindingMap.put(bindingId, bindingFactory); } } ``` 2. 自定义 Interceptor CXF 提供了多种默认的 Interceptor,但是如果需要自定义 Interceptor,可以通过实现 org.apache.cxf.interceptor.Interceptor 接口来完成。下面是一个自定义 Interceptor 的示例: ```java public class CustomInterceptor implements Interceptor<Message> { @Override public void handleMessage(Message message) throws Fault { // 处理请求消息 if (message.getExchange().isOneWay()) { return; } // 处理响应消息 } @Override public void handleFault(Message message) { // 处理异常 } } ``` 3. 自定义 Exception Mapper CXF 提供了多种默认的 Exception Mapper,但是如果需要自定义 Exception Mapper,可以通过实现 org.apache.cxf.jaxrs.ext.ExceptionMapper 接口来完成。下面是一个自定义 Exception Mapper 的示例: ```java public class CustomExceptionMapper implements ExceptionMapper<Exception> { @Override public Response toResponse(Exception exception) { // 处理异常并返回响应 return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(exception.getMessage()) .type(MediaType.TEXT_PLAIN) .build(); } } ``` 4. 自定义 Feature CXF 提供了多种默认的 Feature,但是如果需要自定义 Feature,可以通过实现 org.apache.cxf.feature.Feature 接口来完成。下面是一个自定义 Feature 的示例: ```java public class CustomFeature implements Feature { @Override public void initialize(Server server, Bus bus) { // 初始化服务器 } @Override public void initialize(Client client, Bus bus) { // 初始化客户端 } } ``` 以上是一些 CXF 高级功能的实例,可以根据自己的需求进行定制化开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值