Springboot builds WebService client + server

Introduction to Web Services

Web Service technology enables different applications running on different machines to exchange data or integrate with each other without additional, specialized third-party software or hardware. Applications implemented according to the Web Service specification can exchange data with each other regardless of the language, platform or internal protocol they use.

Simply put, WebService is a remote calling technology across programming languages ​​and operating system platforms. The so-called cross-programming language and cross-operating platform means that the server-side program is written in java, and the client-side program can be written in other programming languages, and vice versa. The cross-operating system platform means that the server program and the client program can run on different operating systems. Remote calling means that an application on one computer can call an application on another computer. For example: Alipay, Alipay does not have data such as bank cards, it just calls the interface provided by the bank to obtain the data. There are also weather forecasts, etc., and the Meteorological Bureau exposes its own system services in the form of webservice services, so that third-party websites and programs can call these service functions.

Principle of Web Service

XML, SOAP and WSDL are the three major technologies that constitute the WebService platform.

  • WebService uses the Http protocol to transmit data between the client and the server. WebService uses XML to encapsulate data. The main advantage of XML is that it is cross-platform.

  • When WebService sends requests and receives results through the HTTP protocol, the sent request content and result content are encapsulated in XML format, and some specific HTTP message headers are added to illustrate the content format of the HTTP message. These specific HTTP message headers and XML The content format is specified by the SOAP protocol.

  • The WebService server first needs to use a WSDL file to explain what services it has that can be called externally. Simply put, WSDL is like a specification for describing WebService and its methods, parameters and return values. A WSDL file is stored on a web server and can be accessed through a url address. Before the client calls a WebService, it needs to know the address of the WSDL file of the service. The WebService service provider can expose its WSDL file address in two ways: 1. Register with the UDDI server so that it can be found by others; 2. Tell the client caller directly.

The process of WebService interaction is that WebService follows the SOAP protocol to encapsulate data through XML, and then transmits the data through the Http protocol.

JAVA WebService specification

There are three WebService specifications in Java, namely JAXM&SAAJ, JAX-WS (JAX-RPC), and JAX-RS.

(1)JAX-WS:

JAX-WS (Java API For XML-WebService). The early SOAP-based JAVA Web service specification JAX-RPC (java API For XML-Remote Procedure Call) has been replaced by the JAX-WS specification. JAX-WS is an evolution of JAX-RPC, but JAX-WS is not completely It is backward compatible with JAX-RPC. The biggest difference between the two is the RPC/encoded style WSDL, which JAX-WS no longer provides. The API of JAX-RPC has been removed since JAVA EE5. If you use J2EE1.4, its API is located in the javax.xml.rpc.package. The API of the JAX-WS (JSR 224) specification is located in the javax.xml.ws. package, most of which are annotations, providing API operations for Web services (usually used more on the client side, because the client side can be generated with the help of the SDK, so APIs in this package are rarely used directly).

(2) JAXM&SAAJ:

  • JAXM (JAVA API For XML Message) mainly defines the API required to send and receive messages, which is equivalent to the server side of the Web service. Its API is located in the javax.messaging.* package, which is an optional package of Java EE, so You need to download it separately.

  • SAAJ (SOAP With Attachment API For Java, JSR 67) is an API used in conjunction with JAXM. It provides important support for building SOAP packages and parsing SOAP packages, and supports attachment transmission. It needs to be used on both the server side and the client side. Also mentioned here is the SAAJ specification, whose API is located in the javax.xml.soap.* package.

  • Both JAXM&SAAJ and JAX-WS are SOAP-based Web services. In contrast, JAXM&SAAJ leaks more underlying details of SOAP, and coding is more troublesome, while JAX-WS is more abstract, hides more details, and is more object-oriented. Basically, you don't need to care about any details of SOAP. So if you want to control more details of the SOAP message, you can use JAXM&SAAJ.

(3)JAX-RS:

JAX-RS is a set of Web service specifications developed by JAVA for the REST (Representation State Transfer) style. Due to its late release, this specification (JSR 311, the current version of JAX-RS is 1.0) has not been released together with JDK1.6 .

Getting started with WebService

Implementation of the server

Let's implement a case of a weather system. The client sends the city name, and the server responds with the corresponding weather.

// 1.  编写SEI(Service Endpoint Interface),SEI在webservice中称为portType,在java中就是普通接口 
package com.wdx.webservice.test2service;

public interface WeatherInterface {
    public String queryWeather(String cityName);
}
//2.  编写SEI实现类,此类作为webservice提供服务类
package com.wdx.webservice.test2service;

import javax.jws.WebService;

@WebService     //@WebService表示该类是一个服务类,需要发布其中的public的方法
public class WeatherInterfaceImpl implements WeatherInterface {

    @Override
    public String queryWeather(String cityName) {
        System.out.println("获取城市名"+cityName);
        String weather="暴雨";
        return weather;
    }

}
// 3.  第三步:发布服务,Endpoint类发布服务,publish方法,两个参数:1.服务地址;2.服务实现类 

public class WeatherServer {
    public static void main(String[] args) {
        Endpoint.publish("http://127.0.0.1:12345/weather", new WeatherInterfaceImpl());
    }
}

//4. 测试服务是否发布成功,通过阅读wsdl,确定客户端调用的接口、方法、参数和返回值存在,证明服务发布成功
//我们在浏览器输入 http://127.0.0.1:12345/weather?wsdl 来获取wsdl文件进行阅读
//wsdl,是以XML文件形式来描述WebService的”说明书”,有了说明书,我们才可以知道如何使用或是调用这个服务.
//现在我们还不知道怎么去阅读,后面我们会详解,只要能获取到,就能确定WebService服务发布成功 

insert image description here

client implementation

//客户端调用服务有很多种方法,我们先用工具生成客户端代码,后面会详解  

//wsimport是jdk自带的webservice客户端工具,可以根据wsdl文档生成客户端调用代码(java代码).当然,无论服务器端的WebService是用什么语言写的,都可以生成调用webservice的客户端代码。

1.创建一个客户端空项目,cmd命令行进入此项目的src目录
  使用以下命令生成客户端代码  

    wsimport -s . http://127.0.0.1:12345/weather?wsdl

    -s是指编译出源代码文件,后面的.(点)指將代码放到当前目录下.
     最后面的http….是指获取wsdl说明书的地址

insert image description here
Create a new client in the generated catalog file

//2.编写客户端
public class WeatherClient {

    public static void main(String[] args) {
        //创建服务视图,视图是从wsdl文件的service标签的name属性获取
        WeatherInterfaceImplService weatherInterfaceImplService=new WeatherInterfaceImplService();  

        //获取服务实现类,实现类从wsdl文件的portType的name属性获取
        WeatherInterfaceImpl weatherInterfaceImpl=weatherInterfaceImplService.getPort(WeatherInterfaceImpl.class); 
        //获取查询方法,从portType的operation标签获取
        String weather=weatherInterfaceImpl.queryWeather("北京");
        System.out.println(weather);

    }

}

At this point, our client can obtain the data of the remote server. Next, let's explain each part in detail.

WSDL

WSDL (Web Services Description Language), web service description language, it is the user manual of the webservice server, which describes the interface, method, parameters and return value of the server. WSDL is automatically generated with the successful release of the service without writing.

document structure

insert image description here

  • Service: A collection of related ports, including their associated interfaces, operations, messages, etc.
  • Binding: specific protocol and data format specification for a specific port type
  • portType: service endpoint, describing the operation method that web service can execute, and related messages, pointing to portType through binding
  • message: defines the data parameters of an operation (method)
  • types: defines all data types used by the web service

reading method

WSDL documents should be read from the bottom up.

1. First look at the service tag, look at the binding attribute of the corresponding port, and then look up the above binding tag through the value.
2. Through the binding tag, you can get the specific protocol and other information, and then check the type attribute of the binding.
3. Through the type attribute of the binding, look up the corresponding portType, and you can get the operable methods, parameters, return values, etc.
4. Through the message attribute of the operation tag under the portType, you can look up the message to obtain specific data parameter information.

Read the wsdl documentation to build the client

  1. Select the port according to wsdl:service. Since we are using http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl here, the port is MobileCodeWSSoap
    insert image description here

  2. Observe wsdl:binding according to wsdl:port value, and select the required method name (such as getMobileCodeInfo) according to wsdl:operation
    insert image description here

  3. Find wsdl:portType and wsdl:operation according to the type value of wsdl:binding, know its input and output,
    insert image description here
    know that the input is tns:getMobileCodeInfoSoapIn; the output is tns:getMobileCodeInfoSoapOut

  4. Look for input and output in wsdl:message
    insert image description here

  5. Find the corresponding value of message in s:element of wsdl:types, and determine the input and output type and number of methods in xs:complexType corresponding to xs:sequence
    insert image description here

Python client construction

from suds.client import Client
import logging

try:
    client = Client('http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl')
    print(client)
    # result = client.service.__getattr__("getMobileCodeInfo")('15118888888')
    result = client.service.__getattr__("getDatabaseInfo")()
except Exception as e:
    logging.error(e)
    # return []
print(type(result))
    # return result
print(result)

Java client construction

import cn.com.webxml.MobileCodeWSSoap;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.io.IOException;
import java.net.URL;

public class MobileClient2 {

    public static void main(String[] args) throws IOException {
        //创建WSDL文件的URL
        URL wsdlDocumentLocation=new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
        //创建服务名称
        //1.namespaceURI - 命名空间地址
        //2.localPart - 服务视图名
        QName serviceName=new QName("http://WebXml.com.cn/","MobileCodeWS");
        Service service= Service.create(wsdlDocumentLocation, serviceName);

        //获取服务实现类
        MobileCodeWSSoap mobileCodeWSSoap= service.getPort(MobileCodeWSSoap.class);
        //调用方法
        String message=mobileCodeWSSoap.getMobileCodeInfo("15118888888", null);
        System.out.println(message);

    }

}

SOAP

SOAP is Simple Object Access Protocol. It is data in XML format sent by http. It can cross platforms and firewalls. SOAP is not a proprietary protocol of webservice.

SOAP=http+xml

SOAP structure

必需的 Envelope 元素,可把此 XML 文档标识为一条 SOAP 消息
可选的 Header 元素,包含头部信息
必需的 Body 元素,包含所有的调用和响应信息
可选的 Fault 元素,提供有关在处理此消息所发生错误的信息

Client calling method of Webservice

1: Generate client call method

wsimport是jdk自带的webservice客户端工具,可以根据wsdl文档生成客户端调用代码(java代码).
wsimport.exe位于JAVA_HOME\bin目录下 
常用参数为:
        -d<目录>  - 将生成.class文件。默认参数。
        -s<目录> - 将生成.java文件。
        -p<生成的新包名> -将生成的类,放于指定的包下

Call the mobile phone attribution query service on the public network
Public network service address (which provides many free calling services)

http://www.webxml.com.cn/zh_cn/index.aspx

第一步:wsimport生成客户端代码 

wsimport -p cn.cad.mobile -s . http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

会出现一些警告,是因为服务端提供的一些方法是SOAP1.2标准的,这个工具没有实现SOAP1.2标准的生成方式。    

insert image description here

 第二步:查看wsdl文件,获取我们需要的信息 

insert image description here

//第三步:根据获取到的服务名等信息来创建我们的客户端  

public class MobileClient {

    public static void main(String[] args) {
        //创建服务视图
        MobileCodeWS mobileCodeWS=new MobileCodeWS();
        //获取服务实现类
        MobileCodeWSSoap mobileCodeWSSoap= mobileCodeWS.getPort(MobileCodeWSSoap.class);
        //调用查询方法
        String message=mobileCodeWSSoap.getMobileCodeInfo("xxxxxxxx", null);
        System.out.println(message);

    }
}

insert image description here

This method is easy to use, but some key elements are hard-coded in the generated code during code generation, which is not convenient for maintenance, so it is only used for testing.

Two: service programming call method

public class MobileClient2 {

    public static void main(String[] args) throws IOException {
        //创建WSDL文件的URL
        URL wsdlDocumentLocation=new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl"); 
        //创建服务名称
        //1.namespaceURI - 命名空间地址
        //2.localPart - 服务视图名
        QName serviceName=new QName("http://WebXml.com.cn/","MobileCodeWS");
        Service service=Service.create(wsdlDocumentLocation, serviceName);

        //获取服务实现类
        MobileCodeWSSoap mobileCodeWSSoap= service.getPort(MobileCodeWSSoap.class);
        //调用方法
        String message=mobileCodeWSSoap.getMobileCodeInfo("XXXXXXX", null);
        System.out.println(message);

    }

}

This method can customize elements such as namespace and service view name, which is convenient for future maintenance and is a standard development method.

Three: HttpURLConnection calling method

This way is to write the client by yourself, no longer generated by the tool, which is more troublesome.

开发步骤: 

        第一步:创建服务地址

        第二步:打开一个通向服务地址的连接

        第三步:设置参数

        第四步:组织SOAP数据,发送请求

        第五步:接收服务端响应 

Modify WSDL content using annotations

Role:
Through annotations, Web services can be described more vividly. Modify the automatically generated wsdl document to provide users with a clearer wsdl document

The annotations of WebService are located under the javax.jws package:

@WebService-定义服务,在类上边
    targetNamespace:指定命名空间
    name:portType的名称
    portName:port的名称
    serviceName:服务名称
    endpointInterface:SEI接口地址,如果一个服务类实现了多个接口,只需要发布一个接口的方法,可通过此注解指定要发布服务的接口。 

@WebMethod-定义方法,在公开方法上边
    operationName:方法名
    exclude:设置为true表示此方法不是webservice方法,反之则表示webservice方法,默认是false 

@WebResult-定义返回值,在方法返回值前边
    name:返回结果值的名称 

@WebParam-定义参数,在方法参数前边
    name:指定参数的名称
//以我们前面做的天气案例为例子

@WebService(
        targetNamespace="http://service.cad.com",
        portName="WeatherSOAPPort",
        serviceName="WeatherWSS",
        name="WeatherSOAP"  
)
public class WeatherInterfaceImpl implements WeatherInterface {

    @WebMethod(
            operationName="getWeather",
            exclude=false
    )
    public @WebResult(name="result")String queryWeather(@WebParam(name="cityName")String cityName) {
        System.out.println("获取城市名"+cityName);
        String weather="暴雨";    
        return weather;
    }

}

Then republish the service, and we can visit the wsdl file again to see what we changed

insert image description here

Reference link: Java implements simple web Service_java webservice interface development_Uncle Ma Porridge's Blog-CSDN Blog
If there is any infringement, please contact Lide

Guess you like

Origin blog.csdn.net/qq_39706515/article/details/130732202