SOAP协议学习和使用

接下来是关于在java中,SOAP的一些相关类和概念。

看之前需要理解SOAP的基本概念。


我们可以想到,在java 程序中发送一个SOAP request,不管是用什么方法,最终发送出去的一定就是一个标准的SOAP request。

只不过java包含一些类,代表了实际的SOAP request中不同部分。以及一些方法,帮助你构造SOAP request中的内容。


首先我们来看看,在java中是如何发送SOAP message的。

  • 第一个类: SOAPConnection

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

SOAPMessage reply = soapConnection.call(loginSOAPRequest, new URL("http://172.28.85.6/ASAPService/ASAPService_V1.svc"));

因此发送SOAP request很简单,只需要构造一个SOAPConnection对象,然后运行call方法。

其中,被发送的loginSOAPRequest是之前构造出来的一个SOAPMessage对象,发送的目的URL就是web service的地址。

由代码可见,web services返回的response也是一个SOAPMessage对象。因此我们可以认定:

在java中,发送和接受的对象都是SOAPMessage。

我们可以进一步认定: SOAPMessage这个对象一定包含了SOAP以及http头的信息。只有这样发送出去的才是一个完整有效的SOAP request。


  • 第二个类:SOAPMessage

首先明确一个概念:虽然SOAPMessage这个对象包含了http头的信息。但是java中并没有单独的类对应http头信息。

因为,http header的信息不需要代码自己构造,而是由java自动完成的。也就是说,在上文中看到的必须的http信息 POST, content_type等信息,都是自动填充的。

我们可以修改这些信息,后面将提到,但是不需要自己构造。


SOAPMessage对象包含两个部分:SOAPPart 和 AttachmentPart.  其中SOAPPart 是必须有的部分,AttachmentPart是可选的部分。

SOAPPart 其实就是完整的SOAP request。它包含http头和SOAP message信息。SOAPPart必须是XML结构的。

AttachmentPart可以有零个或多个,可以理解为,它是SOAP中可以携带的附加信息,例如图片,音频等信息。


SOAPPart  和 AttachmentPart都由下面两个部分组成:

application-specific content and associated MIME headers.


MIME ( Multipurpose Internet Mail Extension) 的概念,在javax.xml.soap有对应的类。只要是这个类的子类就可以使用SOAP传输。

其中MIME headers代表的就是下面的这部分http头信息

POST /item HTTP/1.1
Host: 189.123.345.239
Content-Type: text/plain
Content-Length: 200

SOAPAction: "http://ASAP.services.tfn.**.com/2010-03-01/Login"

但正如前面所说,我们并不需要直接构造这么一个string。SOAPMessage在实例化时会自动构造出默认的MIMEHeader,我们可以修改它:

MimeHeaders hd = loginSOAPRequest.getMimeHeaders(); //loginSOAPRequest是之前构造好的一个SOAPMessage。
hd.setHeader("SOAPAction", "http://ASAP.services.tfn.**.com/2010-03-01/Login";);

//这句将MIMEHeader中包含的SOAPAction部分由默认的“”,修改为指定的样子。

The one new piece here is that SOAP 1.1 requires the client to set a SOAPAction field in the HTTP header.

AttachmentPart可以是非XML结构的。关于AttachmentPart,本文不准备多说。


SOAPMessage类中有很多方法可以用于操作这些包含的对象。

可以使用MessageFactory来创建一个SOAPMessage。然后再向这个message中添加需要的信息。

SOAPMessage可以用来:

  • create a point-to-point connection to a specified endpoint
  • create a SOAP message
  • create an XML fragment
  • add content to the header of a SOAP message
  • add content to the body of a SOAP message
  • create attachment parts and add content to them
  • access/add/modify parts of a SOAP message
  • create/add/modify SOAP fault information
  • extract content from a SOAP message
  • send a SOAP request-response message

  • SOAPPart

看过了SOAPMessage,我们知道SOAPPart其实是SOAP消息的主体。

SOAPMessage包含SOAPPart 对象,SOAPPart 包含了SOAPEnvelope 对象,而SOAPEnvelope 又包含了SOAPBody 和SOAPHeader 对象。如下:

     SOAPPart sp = message.getSOAPPart();
     SOAPEnvelope se = sp.getEnvelope();
     SOAPBody sb = se.getBody();

     SOAPHeader sh = se.getHeader();

正如java API中描述的:SOAPPart object, which contains information used for message routing and identification, and which can contain application-specific content.

上面这些类的层次关系和SOAP协议中的语法结构是一致的。


我们可以方便的创建一个SOAPMessage。此时会有一个默认的SOAPPart属于这个SOAPMessage。

之后我们可以用SOAPPart的方法方便的往SOAPPart中添加信息:

setContent(); //Sets the content of the SOAPEnvelope object with the data from the givenSource object.

联想一下前面各个对象的关系我们就可以知道,这个方法实际set了SOAPEnvelop, SOAPBody. SOAPFault, SOAPHeader。

  • SOAPElement

An object representing an element of a SOAP message that is allowed but not specifically prescribed by a SOAP specification. This interface serves as the base interface for those objects that are specifically prescribed by a SOAP specification.

即element可以代表在SOAPMessag中任何一个element,不管这个element是SOAPBody还是SOAPEnvelope。

  • SOAPFactory

SOAPFactory is a factory for creating various objects that exist in the SOAP XML tree.SOAPFactory can be used to create XML fragments that will eventually end up in the SOAP part.

因此SOAPFactory可以用来读取XML tree,并创建对应的SOAPElement。之后可以方便的将SOAPElement加到SOAPMessage中去。

  • Transformer

它是 javax.xml.soap中另外一个重要的类。在实际应用中,我们会经常使用这个类来将某个XML对象转换成DOM对象。

SOAPElement parent = SOAPFactory.newInstance().createElement("dummy");

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer();

transformer.transform(new DOMSource(doc), new DOMResult(parent));//将XML对象doc转换成DOM对象

return (SOAPElement) parent.getChildElements().next();//取得所有的childElement并返回

通过使用Transformer对象和SOAPElement对象,我们就可以方便的实现读入一个XML,转换成SOAPElement,之后构造成SOAPMessage,最终发送给web service。

也可以将DOM对象转换成XML对象,然后打印输出。


下面是一个极其简单的使用SOAP的示例,从文件读入一个SOAP message并发送给web service

    //Send SOAP request messages and then return response.
    public SOAPMessage sendSOAPMessage() throws Exception {
         

        //用工厂创建一个SOAPMessage
        MessageFactory mf = MessageFactory.newInstance()  ;
        SOAPMessage loginSOAPRequest = mf.createMessage();

        //给这个SOAPMessge添加信息,来源就是d:\\testSOAP.txt文件,内容是标准的SOAP
        SOAPPart sp = loginSOAPRequest.getSOAPPart();
        StreamSource prepMsg = new StreamSource(
                    new FileInputStream("d:\\testSOAP.txt"));
                    sp.setContent(prepMsg);
          
        final String SOAPACTION = "http://ASAP.services.tfn.thomson.com/2010-03-01/Login";
        //将SOAPAction添加到MimeHeaders中去
        MimeHeaders hd = loginSOAPRequest.getMimeHeaders();
        hd.setHeader("SOAPAction", SOAPACTION);

        //将上面的更改保存
        loginSOAPRequest.saveChanges();
        //创建一个SOAPConnection。具体方法在前面的SOAPConnection中已经说了         
        SOAPConnection con = getSoapConnection();
        //发送SOAP request 。这里目标地址可以是web services或tornado。
        SOAPMessage reply = con.call(loginSOAPRequest, new URL("http://172.28.85.6/ASAPService/ASAPService_V1.svc"));
        con.close();
        //返回response
        return reply;        
    }

下面这个方法接收一个SOAPMessage,并将其内容打印到文件中。据此我们可以检查构造的SOAPMessage是否是自己希望的内容。

private void getSoapContent(SOAPMessage loginSOAPRequest) {
          String output = "d:\\test1.txt";
          try{
          FileOutputStream tt = new FileOutputStream(output);
          loginSOAPRequest.writeTo(tt);
          tt.toString();
          }catch(Exception e){
              System.out.println();
          }
          
      }


一个需要知道的名词:

SAAJ refer to SOAP with Attachments API for JavaTM (SAAJ)


其他可以参考的代码示例是:

http://technet.rapaport.com/Info/Prices/SampleCode/Java_Webservice_Example.aspx

http://java.boot.by/wsd-guide/ch05s04.html

下面是一个使用例子:
目录结构:
在这里插入图片描述
添加依赖:

<dependency>
    <groupId>javax.xml.soap</groupId>
    <artifactId>javax.xml.soap-api</artifactId>
    <version>1.4.0</version>
</dependency>
package com.my.demo.soap.config;
import com.my.demo.soap.service.DemoWebService;
import com.my.demo.soap.service.TestWebService;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

/**
 * 注意:
 * org.apache.cxf.Bus
 * org.apache.cxf.bus.spring.SpringBus
 * org.apache.cxf.jaxws.EndpointImpl
 * javax.xml.ws.Endpoint
 * @date 2020/11/19 20:38
 */
@Configuration
public class WebServiceConfiguration {


    @Autowired
    private DemoWebService demoWebService;

    @Autowired
    private TestWebService testWebService;

    /**
     * Apache CXF 核心架构是以BUS为核心,整合其他组件。
     * Bus是CXF的主干, 为共享资源提供一个可配置的场所,作用类似于Spring的ApplicationContext,这些共享资源包括
     * WSDl管理器、绑定工厂等。通过对BUS进行扩展,可以方便地容纳自己的资源,或者替换现有的资源。默认Bus实现基于Spring架构,
     * 通过依赖注入,在运行时将组件串联起来。BusFactory负责Bus的创建。默认的BusFactory是SpringBusFactory,对应于默认
     * 的Bus实现。在构造过程中,SpringBusFactory会搜索META-INF/cxf(包含在 CXF 的jar中)下的所有bean配置文件。
     * 根据这些配置文件构建一个ApplicationContext。开发者也可以提供自己的配置文件来定制Bus。
     */
    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

  


  /**
     * 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问
     * 此方法被注释后, 即不改变前缀名(默认是services), wsdl访问地址为 http://127.0.0.1:8080/services/ws/api?wsdl
     * 去掉注释后wsdl访问地址为:http://127.0.0.1:8080/soap/ws/api?wsdl
     * http://127.0.0.1:8080/soap/列出服务列表 或 http://127.0.0.1:8080/soap/ws/api?wsdl 查看实际的服务
     * 新建Servlet记得需要在启动类添加注解:@ServletComponentScan
     * <p>
     * 如果启动时出现错误:not loaded because DispatcherServlet Registration found non dispatcher servlet dispatcherServlet
     * 可能是springboot与cfx版本不兼容。
     * 同时在spring boot2.0.6之后的版本与xcf集成,不需要在定义以下方法,直接在application.properties配置文件中添加:
     * cxf.path=/service(默认是services)
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
    }

    @Bean
    public Endpoint endpoint() {
        Endpoint endpoint = new EndpointImpl(springBus(), demoWebService);
        endpoint.publish("/ws/api");
        return endpoint;
    }

    @Bean
    public Endpoint endpoint2() {
        Endpoint endpoint1 = new EndpointImpl(springBus(), testWebService);
        endpoint1.publish("/ws/api2");
        return endpoint1;
    }
}
package com.my.demo.soap.controller;

import com.my.demo.soap.service.DemoWebService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestSoapController {

    @Autowired
    private DemoWebService demoWebService;

    @ApiOperation(value = "测试接口")
    @GetMapping("/hello")
    public String hello(@ApiParam(value = "用户名", required = false) @RequestParam String userName) {
        //SoapUtil.testSoap3();
        return demoWebService.hello(userName);
    }
}
package com.my.demo.soap.service;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.HashMap;

/**
 * @date 2020/11/19 20:27
 */
@WebService(name = TestWebService.WEBSERVICE_NAME, targetNamespace = TestWebService.TARGET_NAMESPACE)
public interface TestWebService {

    String WEBSERVICE_NAME = "TestWebService";
    String TARGET_NAMESPACE = "http://test.webservice.com";
    String WEBSERVICE_INTERFACE_NAME = "com.my.demo.soap.service.TestWebService";

    @WebMethod
    String test1(@WebParam(name = "userName3") String name);

    @WebMethod
    String test2(@WebParam(name="headerMap") HashMap<String, String> headerMap, @WebParam HashMap<String, String> parameterMap, @WebParam String bodyJson);

}
package com.my.demo.soap.service;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.HashMap;

/**
 * @date 2020/11/19 20:27
 */
@WebService(name = DemoWebService.WEBSERVICE_NAME, targetNamespace = DemoWebService.TARGET_NAMESPACE)
public interface DemoWebService {

    String WEBSERVICE_NAME = "DemoWebService";
    String TARGET_NAMESPACE = "http://demo.webservice.com";
    String WEBSERVICE_INTERFACE_NAME = "com.my.demo.soap.service.DemoWebService";

    @WebMethod
    String hello(@WebParam(name = "userName3") String name);

    @WebMethod
    String test(@WebParam(name="headerMap") HashMap<String, String> headerMap, @WebParam HashMap<String, String> parameterMap, @WebParam String bodyJson);

}
package com.my.demo.soap.service.impl;
import com.my.demo.soap.service.DemoWebService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import java.util.HashMap;

/**
 * WebService涉及到的有这些 "四解三类 ", 即四个注解,三个类
 *
 * @WebMethod
 * @WebService
 * @WebResult
 * @WebParam SpringBus
 * Endpoint
 * EndpointImpl
 * <p>
 * 一般我们都会写一个接口,然后再写一个实现接口的实现类,但是这不是强制性的
 * @WebService 注解表明是一个webservice服务。
 * name:对外发布的服务名, 对应于<wsdl:portType name="ServerServiceDemo"></wsdl:portType>
 * targetNamespace:命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误
 * Exception in thread "main" org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx
 * 对应于targetNamespace="http://server.webservice.example.com"
 * endpointInterface:服务接口全路径(如果是没有接口,直接写实现类的,该属性不用配置), 指定做SEI(Service EndPoint Interface)服务端点接口
 * serviceName:对应于<wsdl:service name="ServerServiceDemoImplService"></wsdl:service>
 * portName:对应于<wsdl:port binding="tns:ServerServiceDemoImplServiceSoapBinding" name="ServerServiceDemoPort"></wsdl:port>
 * @WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在,在接口方法已加上@WebMethod, 所以在实现类中不用再加上,否则就要加上
 * operationName: 接口的方法名
 * action: 没发现又什么用处
 * exclude: 默认是false, 用于阻止将某一继承方法公开为web服务
 * @WebResult 表示方法的返回值
 * name:返回值的名称
 * partName:
 * targetNamespace:
 * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 * @WebParam name:接口的参数
 * partName:
 * targetNamespace:
 * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 * model:WebParam.Mode.IN/OUT/INOUT
 * @date 2020/11/19 20:29
 */
@Component
@WebService(name = DemoWebService.WEBSERVICE_NAME, targetNamespace = DemoWebService.TARGET_NAMESPACE,
        endpointInterface = DemoWebService.WEBSERVICE_INTERFACE_NAME)
public class DemoWebServiceImpl implements DemoWebService {

    @Override
    public String hello(String userName) {
        if (StringUtils.isBlank(userName)) {
            return "传入的name为空";
        }
        return "Hello: ".concat(userName);
    }

    @Override
    public String test(HashMap<String, String> headerMap, HashMap<String, String> parameterMap, String bodyJson) {
        return "mapParameters";
    }
}
package com.my.demo.soap.service.impl;
import com.my.demo.soap.service.DemoWebService;
import com.my.demo.soap.service.TestWebService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import java.util.HashMap;

/**
 * WebService涉及到的有这些 "四解三类 ", 即四个注解,三个类
 *
 * @WebMethod
 * @WebService
 * @WebResult
 * @WebParam SpringBus
 * Endpoint
 * EndpointImpl
 * <p>
 * 一般我们都会写一个接口,然后再写一个实现接口的实现类,但是这不是强制性的
 * @WebService 注解表明是一个webservice服务。
 * name:对外发布的服务名, 对应于<wsdl:portType name="ServerServiceDemo"></wsdl:portType>
 * targetNamespace:命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误
 * Exception in thread "main" org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx
 * 对应于targetNamespace="http://server.webservice.example.com"
 * endpointInterface:服务接口全路径(如果是没有接口,直接写实现类的,该属性不用配置), 指定做SEI(Service EndPoint Interface)服务端点接口
 * serviceName:对应于<wsdl:service name="ServerServiceDemoImplService"></wsdl:service>
 * portName:对应于<wsdl:port binding="tns:ServerServiceDemoImplServiceSoapBinding" name="ServerServiceDemoPort"></wsdl:port>
 * @WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在,在接口方法已加上@WebMethod, 所以在实现类中不用再加上,否则就要加上
 * operationName: 接口的方法名
 * action: 没发现又什么用处
 * exclude: 默认是false, 用于阻止将某一继承方法公开为web服务
 * @WebResult 表示方法的返回值
 * name:返回值的名称
 * partName:
 * targetNamespace:
 * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 * @WebParam name:接口的参数
 * partName:
 * targetNamespace:
 * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 * model:WebParam.Mode.IN/OUT/INOUT
 * @date 2020/11/19 20:29
 */
@Component
@WebService(name = TestWebService.WEBSERVICE_NAME, targetNamespace = TestWebService.TARGET_NAMESPACE,
        endpointInterface = TestWebService.WEBSERVICE_INTERFACE_NAME)
public class TestWebServiceImpl implements TestWebService {

    @Override
    public String test1(String userName) {
        if (StringUtils.isBlank(userName)) {
            return "传入的name为空";
        }
        return "Hello: ".concat(userName);
    }

    @Override
    public String test2(HashMap<String, String> headerMap, HashMap<String, String> parameterMap, String bodyJson) {
        return "mapParameters";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值