Webservice入门概念以及发送端与消费端demo

webservice入门以及发送端与消费端demo

本文地址: https://blog.csdn.net/renhuan28/article/details/87808633

  1. 概念

​ WebService是一种跨编程语言和跨操作系统平台的远程调用技术,从表面上看,WebService就是一个应用程序向外界暴露出一个能通过Web进行调用的API,也就是说能用编程的方法通过Web来调用这个应用程序。我们把调用这个WebService的应用程序叫做客户端,而把提供这个WebService的应用程序叫做服务端。从深层次看,WebService是建立可互操作的分布式应用程序的新平台,是一个平台,是一套标准。它定义了应用程序如何在Web上实现互操作性。XML+XSD,SOAP和WSDL是构成WebService平台的三大技术;并且WebService服务提供商可以通过两种方式来暴露它的WSDL文件地址:

1.注册到UDDI服务器,以便被人查找;
2.直接告诉给客户端调用者。

XML+XSD:WebService采用HTTP协议作为传输协议,采用XMl格式封装数据,XML的优点在于它与平台和语言无关,XSD(XML Schema)来定义一套标准的数据类型,无论你使用什么语言的数据类型都会被转换为XSD类型。

SOAP(Simple Object Access Protocol):WebService通过HTTP协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。

WSDL:用于描述WebService及其函数、参数和返回值的XML。一些最新的开发工具既能根据你的Web service生成WSDL文档,又能导入WSDL文档,生成调用相应WebService的代理类代码。

UUDI:一种目录服务,企业可以使用它对Webservices进行注册和搜索

此段转自:
原文:https://blog.csdn.net/yutao_struggle/article/details/80829770

  • 服务端demo

    利用SpringBoot和CXF框架写的webservice服务端demo

  • pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
      </parent>
      <groupId>raptor.happy</groupId>
      <artifactId>webserviceser</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <name>webserviceser</name>
      <description>Demo project for Spring Boot</description>
    
      <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <dependencies>
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
    
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <dependency>
          <groupId>wsdl4j</groupId>
          <artifactId>wsdl4j</artifactId>
          <version>1.6.3</version>
        </dependency>
    
        <!--<dependency>-->
          <!--<groupId>org.apache.cxf</groupId>-->
          <!--<artifactId>cxf-rt-frontend-jaxws</artifactId>-->
          <!--<version>3.1.6</version>-->
        <!--</dependency>-->
        <!--<dependency>-->
          <!--<groupId>org.apache.cxf</groupId>-->
          <!--<artifactId>cxf-rt-transports-http</artifactId>-->
          <!--<version>3.1.6</version>-->
        <!--</dependency>-->
        <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
          <version>3.1.12</version>
        </dependency>
    
    
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
        </plugins>
      </build>
    
    </project>
    
  • 接口

    package raptor.happy.service;
    
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    
    @WebService(name = "CXFWebservice", targetNamespace = "www.service.happy.raptor")
    public interface CXFWebservice {
    
      @WebMethod
      @WebResult(name = "String", targetNamespace = "")
      public String yourName(@WebParam(name = "studentNO") String studentNo);
    
    }
    
  • 接口实现类

    package raptor.happy.service;
    
    import javax.jws.WebService;
    import org.springframework.stereotype.Component;
    
    @WebService(name = "CXFWebservice", targetNamespace = "www.service.happy.raptor", endpointInterface = "raptor.happy.service.CXFWebservice")
    @Component
    public class CXFWebserviceImpl implements CXFWebservice {
    
      @Override
      public String yourName(String studentNo) {
        return "Your studentNo is " + studentNo + ",and YourName is zhangsan";
      }
    }
    
  • CXF配置类

    package raptor.happy.config;
    
    import javax.xml.ws.Endpoint;
    import org.apache.cxf.Bus;
    import org.apache.cxf.jaxws.EndpointImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import raptor.happy.service.CXFWebservice;
    
    @Configuration
    public class CxfWebserviceConfig {
    
      @Autowired
      private Bus bus;
    
      @Autowired
      CXFWebservice cxfWebservice;
    
      /*jax-ws*/
      @Bean
      public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, cxfWebservice);
        endpoint.publish("/CXFWebservice");
        return endpoint;
      }
    }
    
  • 启动服务,输入地址,本机是http://localhost:8090/services/CXFWebservice?wsdl

    可以看到:
    This XML file does not appear to have any style information associated with it. The document tree is shown below.
    <wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="www.service.happy.raptor" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="CXFWebserviceImplService" targetNamespace="www.service.happy.raptor">
    <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="www.service.happy.raptor" elementFormDefault="unqualified" targetNamespace="www.service.happy.raptor" version="1.0">
    <xs:element name="yourName" type="tns:yourName"/>
    <xs:element name="yourNameResponse" type="tns:yourNameResponse"/>
    <xs:complexType name="yourName">
    <xs:sequence>
    <xs:element minOccurs="0" name="studentNO" type="xs:string"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="yourNameResponse">
    <xs:sequence>
    <xs:element minOccurs="0" name="String" type="xs:string"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>
    </wsdl:types>
    <wsdl:message name="yourNameResponse">
    <wsdl:part element="tns:yourNameResponse" name="parameters"></wsdl:part>
    </wsdl:message>
    <wsdl:message name="yourName">
    <wsdl:part element="tns:yourName" name="parameters"></wsdl:part>
    </wsdl:message>
    <wsdl:portType name="CXFWebservice">
    <wsdl:operation name="yourName">
    <wsdl:input message="tns:yourName" name="yourName"></wsdl:input>
    <wsdl:output message="tns:yourNameResponse" name="yourNameResponse"></wsdl:output>
    </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="CXFWebserviceImplServiceSoapBinding" type="tns:CXFWebservice">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="yourName">
    <soap:operation soapAction="" style="document"/>
    <wsdl:input name="yourName">
    <soap:body use="literal"/>
    </wsdl:input>
    <wsdl:output name="yourNameResponse">
    <soap:body use="literal"/>
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="CXFWebserviceImplService">
    <wsdl:port binding="tns:CXFWebserviceImplServiceSoapBinding" name="CXFWebservicePort">
    <soap:address location="http://localhost:8090/services/CXFWebservice"/>
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    

    这便是服务端的WSDL文档,这里有对接口名,参数等的详细描述。

  • 再提供个不用springboot的配置类

    package raptor.happy.config;
    
    import org.apache.cxf.Bus;
    import org.apache.cxf.bus.spring.SpringBus;
    import org.apache.cxf.transport.servlet.CXFServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import raptor.happy.service.Demoservice;
    import raptor.happy.service.DemoserviceImpl;
    import javax.xml.ws.Endpoint;
    
    import org.apache.cxf.jaxws.EndpointImpl;
    
    @Configuration
    public class CxfConfig {
    
      @Bean
      public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/demo/*");
      }
    
      @Bean(name = Bus.DEFAULT_BUS_ID)
      public SpringBus springBus() {
        return new SpringBus();
      }
    
      @Bean
      public CXFWebservice cxfWebservice() {
        return new CXFWebserviceImpl();
      }
    
      @Bean
      public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), cxfWebservice());
        endpoint.publish("/CXFWebservice");
        return endpoint;
      }
    }
    

    启动后本机地址是http://localhost:8090/demo/CXFWebservice?wsdl

    注意以上代码对ServletRegistrationBean目录进行过更改。

  • 客户端demo

    先利用SpringBoot和CXF框架写的webservice服务端demo

  • pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.6.RELEASE</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>raptor.happy</groupId>
    	<artifactId>websercicecli</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>websercicecli</name>
    	<description>Demo project for Spring Boot</description>
    
    	<properties>
    		<java.version>1.7</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.12</version>
    			<scope>test</scope>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web-services</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    
    
    		<dependency>
    			<groupId>commons-httpclient</groupId>
    			<artifactId>commons-httpclient</artifactId>
    			<version>3.1</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.apache.cxf</groupId>
    			<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    			<version>3.1.12</version>
    		</dependency>
    
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    
  • 利用CXF调接口

    package raptor.happy.cxfSend;
    
    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
    
    public class CxfWebSerciceSend {
    
      public String sendOne() {
    
        // 创建客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://localhost:8090/services/CXFWebservice?wsdl");
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,
        // PASS_WORD));
        Object[] objects = new Object[0];
        try {
          // invoke("方法名",参数1,参数2,参数3....);
          objects = client.invoke("yourName", "lisi");
          return "返回数据:" + objects[0];
        } catch (java.lang.Exception e) {
          e.printStackTrace();
          return "异常:" + e.getMessage();
        }
      }
    }
    
    • 测试类
    package raptor.happy;
    
    import mypackage.DemoserviceImplService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import raptor.happy.cxfSend.CxfWebSerciceSend;
    import raptor.happy.send.WebserviceSend;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class WebsercicecliApplicationTests {
    
    	@Test
    	public void contextLoads() {
    		CxfWebSerciceSend cxfWebSerciceSend = new CxfWebSerciceSend();
    		String result3 = cxfWebSerciceSend.sendOne();
    		System.out.println("===========================================");
    		System.out.println(result3);
    		System.out.println("===========================================");
    	}
    
    }
    
    
    

    再写个不用CXF框架调服务端接口

    • 调接口代码, 自己利用soap协议写消息信息。soap request格式可以通过soapUI工具调url看到。通过Http post发送,获得响应信息。
    package raptor.happy.send;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.SimpleHttpConnectionManager;
    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.RequestEntity;
    
    public class WebserviceSend {
    
      public String doSend() {
    
        String msg = buildMsg();
    
        return doMsgSend(msg).toString();
      }
    
      private Map doMsgSend(String msg) {
    
        Map<String, String> response = new HashMap<>();
        String url = "http://localhost:8090/services/CXFWebservice?wsdl";
    
        PostMethod postMethod = null;
        HttpClient httpClient = null;
    
        postMethod = new PostMethod(url);
        int statusCode;
        try {
          byte[] b = msg.getBytes("UTF-8");
          StringBuffer responseBody = new StringBuffer();
          InputStream is = new ByteArrayInputStream(b, 0, b.length);
          RequestEntity re =
              new InputStreamRequestEntity(is, b.length, "text/xml;charset=UTF-8;soapaction = ''");
          postMethod.setRequestEntity(re);
          postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate");
          postMethod.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
          postMethod.setRequestHeader("SOAPAction", "\"\"");
          httpClient = new HttpClient();
          httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
          httpClient.getParams().setConnectionManagerTimeout(30 * 1000);
          httpClient.getParams().setSoTimeout(30 * 1000);
          statusCode = httpClient.executeMethod(postMethod);
          InputStream inputStream = postMethod.getResponseBodyAsStream();
          BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
          String str = "";
          while ((str = br.readLine()) != null) {
            responseBody.append(str);
          }
          if (statusCode != 200) {
            response.put("statusCode", String.valueOf(statusCode));
            response.put("result", "false");
            response.put("responseBody", responseBody.toString());
            return response;
          }
          response.put("statusCode", "0000");
          response.put("result", "true");
          response.put("responseBody", responseBody.toString());
        } catch (IOException e) {
          response.put("statusCode", "2000");
          response.put("result", "false");
          response.put("responseBody", e.getMessage());
        }
    
        return response;
      }
    
      private String buildMsg() {
        StringBuffer msgString = new StringBuffer();
    
        msgString.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"www.service.happy.raptor\">\n"
            + "   <soapenv:Header/>\n"
            + "   <soapenv:Body>\n"
            + "      <ser:yourName>\n"
            + "         <!--Optional:-->\n"
            + "         <studentNO>lisi</studentNO>\n"
            + "      </ser:yourName>\n"
            + "   </soapenv:Body>\n"
            + "</soapenv:Envelope>");
        return msgString.toString();
      }
    
    }
    
    • 测试类
    package raptor.happy;
    
    import mypackage.DemoserviceImplService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import raptor.happy.cxfSend.CxfWebSerciceSend;
    import raptor.happy.send.WebserviceSend;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class WebsercicecliApplicationTests {
    
    	@Test
    	public void contextLoads() {
    
    		WebserviceSend webserviceSend = new WebserviceSend();
    		String result2 = webserviceSend.doSend();
    		System.out.println("===========================================");
    		System.out.println(result2);
    		System.out.println("===========================================");
    	}
    }
    

​ 客户端还有一种方法,我用的IDEA开发工具,可以选中工程目录,点tool-webservice-Generate Javacode From Wsdl ,注意要选中你要生成code的包,

​ 然后在弹出的对话框里输入wsdl url,code输出位置路径,输出package名字等信息,Web Service Platform

选择 Glassfish /JAX-WS 2.2 RI的。然后便会在目标路径生成一些类。(截图不会传)

​ 测试类直接调

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebsercicecliApplicationTests {

	@Test
	public void contextLoads() {
		//生成发服务接口实现类
		DemoserviceImplService webServiceImpl = new DemoserviceImplService();
		//调实现类方法,这里是方法是sayHello
		String result = webServiceImpl.getDemoserviceImplPort().sayHello("没有说");;
		System.out.println("===========================================");
		System.out.println(result);
		System.out.println("===========================================");
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值