WebService concise tutorial

Posted by ericdorman on Tue, 01 Mar 2022 02:07:39 +0100

There are thousands of people in the vast sea. Thank you for seeing here this second. I hope my article is helpful to you!

May you keep your love and go to the mountains and seas in the future!

👀 preface

Because some time ago, we need to use webService to call other system api interfaces of the company, but the request method is different from the http request I am familiar with. It is based on soap Protocol to transmit xml data format. The parameters of the request are extremely complex and need to encapsulate multi-layer xml data format, and I don't know what language the other party's api interface is, I don't even know what platform they exist on.

How is this different from our common HTTP API interface?

  • Different protocols: http service is based on HTTP protocol, while web service is based on soap Protocol;
  • Different data processing efficiency: http service is more efficient, transmitting strings, while web service is packaged into more complex objects, so that it can process more complex data types;
  • Whether it can be handled across domains: HttpService cannot handle cross domains. If you call a service of other applications, you need to use webService, just as I call the services of other systems now.

😀 summary

😆 Introduce

WebService is mainly a software service provided on the Web through SOAP protocol. It is described with WSDL document and registered through UDDI. WebService is a remote calling technology across programming languages and operating system platforms, which can make different applications running on different machines exchange data or integrate with each other without the help of additional and special third-party software or hardware. Applications implemented according to the Web service specification can exchange data with each other no matter what language, platform or internal protocol they use.

So, if you want to use different languages, different platforms and different places for data transmission, it's right to choose WebService under self recommendation!

🔄 Multidimensional understanding

  • On the surface, WebService is an application that exposes an API that can be called through the Web to the outside world, that is, the application can be called through the Web through programming methods. We call the application that calls this WebService the client, and the application that provides this WebService the server.
  • From the inner layer, WebService is not a technology, but more like a new platform based on interoperable distributed applications. It is a platform, a set of standards and a specification. It defines how applications can achieve interoperability on the Web. You can write WebServices in any language you like and on any platform you like, as long as we can query and access these services through WebService standards.

👩‍👧‍đŸ‘Ļ Three good brothers

It is often accompanied by three element brothers: UDDI, WSDL and SOAP

  • UDDI: UDDI is a technology used to describe, discover and integrate Web services. It is an important part of the Web Service protocol stack. Through UDDI, enterprises can dynamically find and use web services according to their own needs, or dynamically publish their own web services to the UDDI registry for use by other users. UDDI uses SOAP message mechanism (standard XML/HTTP) to publish, edit, browse and find registration information. It uses XML format to encapsulate various types of data, and sends it to the registry or the registry returns the required data.

  • WSDL: it is to describe the XML format of Web service publishing. It is a formal description document provided in a way that can be read by the machine, and a language based on XML (a subset of the standard General Markup Language) is used to describe WebService and its functions, parameters and return values. Because it is based on XML, WSDL is both machine readable and human readable.

  • Soap: simple object access protocol is a protocol specification for exchanging data. It is a lightweight, simple protocol based on XML standard (a subset of General Markup Language). It is mainly composed of HTTP protocol and XML data format. When WebService sends requests and receives results through HTTP protocol, the sent request content and result content are encapsulated in XML format, and some specific HTTP message headers are added to explain the content format of HTTP messages. These specific HTTP message headers and XML content formats are SOAP Protocol. Soap provides a standard RPC (remote call technology) method to call WebService.

😎 Benefits of choice

  1. Cross platform call.
  2. Cross language call.
  3. Remote call.

😜 Let's get started

If you don't say much, you might as well make a small demo and test it yourself. So Let's GO!

Make a demo of the weather system, the client sends the city name, and the server responds to the corresponding weather.

📖 Create an empty project

Create an empty project weatherServer. The IDEA version I use is 2020.3. Of course, I introduced it in detail at the beginning

🍉 Implementation of publishing server

1. Create the server module weatherServerTest

The creation process is basically similar. If you want to choose to use me, I will suggest you create a server first so that others can access or use other people's server. Here, a server module will be created first, and the subsequent creation of client modules is basically similar. Here, we can directly select a Maven project or choose an ordinary Java project by ourselves. JDK is the popular JDK8.

The final empty module server is as follows:

2. Provision of weather services

The next step is to develop the server code. Provide simple urban weather services.

  1. Define a weather service interface IWeatherService

    The code is as follows:

    package com.ws.service;
    public interface IWeatherSerice {
         * Get the corresponding weather by city name
         * @param city city
         * @return weather
        public String queryWeather(String city);
  2. Write the corresponding interface implementation class WeatherServiceImpl

    The corresponding codes are as follows:

    package com.ws.service.impl;
    import com.ws.service.IWeatherSerice;
    import javax.jws.WebService;
    @WebService  // Using this annotation to modify indicates that the current class is a service class that must be added, otherwise an error will be reported when starting the service.
    public class WeatherServiceImpl implements IWeatherSerice {
        public String queryWeather(String city) {
            // Directly return to the corresponding city and sunny day here!!!
            return city + "The weather is: Sunny!";
  3. Create a class WeatherServerDemo for publishing services.

    The corresponding codes are as follows:

    package com.ws.server;
    import com.ws.service.impl.WeatherServiceImpl;
    import javax.xml.ws.Endpoint;
    public class WeatherServerDemo {
        public static void main(String[] args) {
             * address: Service address -- > the address provided for access
             * implementor: Service class -- > the implementation class of the interface that provides access
            Endpoint.publish("http://localhost:8086/weatherServer", new WeatherServiceImpl());
            System.out.println("Service published successfully");
  4. Run the main method to start the service:

    You can see that the console does not close after running, and shows that the service has been published successfully. Next, let's take a look at our services online.

3. Access services

Access the address just provided plus? WSDL, such as: http://localhost:8086/weatherServer?wsdl

How do you view this wsdl document? No, let me show you some important parts at a glance! Note: wsdl documents need to be viewed from the bottom up

  • : service view name, service endpoint of WebService
  • : the communication protocol of web service, and also describes the method, input and output of web service.
  • : describes the operations that WebService can perform, and points to portType through binding
  • : describes the methods published in the service, including parameters, return values, etc.
  • : defines the data types used in the WebService

Visit a detailed parameter page: http://localhost:8086/weatherServer?xsd=1

🍊 Several ways to realize client access

1. Create the client module weatherClientTest


2. Generate corresponding client code

Why do you need to download the client code? First, the first two methods need to use the interface of the server code. Then if you access the remote server, you can't access it.

Here we will introduce the command of jdk: wsimport

wsimport yes jdk Self contained webservice Client tools,Can be based on wsdl Document generation client calling code(java code).
wsimport.exe be located JAVA_HOME\bin Under the directory 
Common parameters are:
        -d<catalogue>  - Will generate.class Documents. Default parameters.
        -s<catalogue> - Will generate.java Documents.
        -p<New package name generated> -Put the generated class under the specified package
wsimport -s ./ http://localhost:8086/weatherServer?wsdl

Generation steps:

  • Enter the java directory of src of the client module

  • In this directory, enter command line mode and enter wsimport - S/ http://localhost:8086/weatherServer?wsdl , download the server code just started. Note: this step must ensure that the server is started and accessible.

  • The structure of the final generated code in IDEA is:

The code obtained here can correspond to the corresponding name of the wsdl document one by one. Of course, if you want to change the package name, you can use the - p parameter.

3. Client access method 1

The first method: call the service method through the obtained code.

The structure is as follows:

The code is as follows:

package com.ws.client;

import com.ws.service.impl.WeatherServiceImpl;
import com.ws.service.impl.WeatherServiceImplService;

public class WeatherClientDemo1 {
    public static void main(String[] args) {
        // 1. Create service view
        WeatherServiceImplService weatherServiceImplService = new WeatherServiceImplService();

        // 2. Get service implementation class
        WeatherServiceImpl weatherService = weatherServiceImplService.getPort(WeatherServiceImpl.class);

        // 3. Method of calling interface
        String result = weatherService.queryWeather("Guangzhou");

        // 4. Return the result of remote access -- > result = the weather in Guangzhou is sunny!
        System.out.println("result = " + result);

Finally, the results obtained after our operation are just as expected:

4. Client access mode 2

What are the defects of the previous step? It should be very clear: we have fixed a service address, and if we want to change the service address, we may need to generate the code again.

So we write out the service address, and the structure is as follows:

The code is as follows:

package com.ws.client;

import com.ws.service.impl.WeatherServiceImpl;
import com.ws.service.impl.WeatherServiceImplService;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;

public class WeatherClientDemo2 {
    public static void main(String[] args) throws Exception {
        // 1. Set the server address to access
        URL url = new URL("http://localhost:8086/weatherServer?wsdl");
            2.Set service name and namespace
             namespaceURI: wsdl Namespace of (targetNamespace)
             localPart: Is the name of the service view (the name value of the service)
        QName qName = new QName("http://impl.service.ws.com/", "WeatherServiceImplService");
        // 3. Generate service view
        Service service = Service.create(url, qName);
        // 4. Get the implementation class of the service view -- > weatherserviceimpl
        WeatherServiceImpl weatherServiceImpl = service.getPort(WeatherServiceImpl.class);

        // 5. Call the interface method to get the result! -- > Result = the weather in Shenzhen is sunny!
        String result = weatherServiceImpl.queryWeather("Shenzhen");
        System.out.println("result = " + result);

Where are these corresponding parameters in wsdl? Let me show you:

This second way is a more commonly used way, first recommended!

5. Client access method 3

If you do not need to download the server code, you can access the server through HTTP urlconnection. The code here is relatively long, and you need to define XML strings and parse strings by yourself.

  1. In POM Add a dom4j dependency package to the XML file


    The structure is as follows:

  2. Create the corresponding test demo. The general structure is as follows:

    The code is as follows: you can copy it to IDEA and watch it carefully.

    package com.ws.client;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Node;
    import java.io.DataOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Scanner;
    public class WeatherClientDemo3 {
        public static void main(String[] args) throws Exception {
            // 1. Set the server address to access
            URL url = new URL("http://localhost:8086/weatherServer?wsdl");
            // 2. Open a connection to the service address
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. Set the parameter, -- > post must be capitalized, otherwise an exception will be thrown
            // This is text/xml, not text/html
            connection.setRequestProperty("content-Type", "text/xml;charset=utf-8");
            // 4. Set input / output. The default value is false. You do not have read / write permission
            // Send SOAP request, 5. Organize data
            String soapXml = getXmlString("Foshan");
            System.out.println("soapXml = " + soapXml);
            // 6. Write data to the output stream
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            // 7. Judge whether the remote access is successful. If the response code is 200, it is successful
            if (connection.getResponseCode() == 200) {
                // 8. Get the corresponding input stream and get the corresponding result
                InputStream ips = connection.getInputStream();
                Scanner scanner = new Scanner(ips);
                StringBuffer buffer = new StringBuffer();
                while (scanner.hasNextLine()) {
                // Get as xml string
                System.out.println("buffer = " + buffer);
                // 9. Parse the xml string to get the returned string
                String xml = parseXmlToString(buffer);
                System.out.println("xml = " + xml);
        private static String parseXmlToString(StringBuffer buffer) {
            try {
                // Get the corresponding document object
                Document document = DocumentHelper.parseText(buffer.toString());
                // "/ /" select a node named item from any node.
                Node node = document.selectSingleNode("//return");
                return node.getText();
            } catch (DocumentException e) {
            return null;
        private static String getXmlString(String string) {
            String xml = "<?xml version=\"1.0\" ?>"
                    + "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                    + "<S:Body>" + "<ns2:queryWeather xmlns:ns2=\"http://impl.service.ws.com/\">"
                    + "<arg0>" + string
                    + "</arg0>" + "</ns2:queryWeather>" + "</S:Body>"
                    + "</S:Envelope>\"";
            return xml;
  3. Results obtained:

    It can be seen that the corresponding results can be obtained.

6. Comparison of three methods

  1. The first method: Although the code is relatively simple, it has a high degree of coupling and can only be applied to the address of the currently downloaded server. Generally, after the server is started, the interface methods and parameters will not change much. However, if the address changes, you need to download the server code again.
  2. The second method: on the basis of the first method, extract the server access address, so that we can configure the corresponding service access address in configuration files such as xml files. Once it needs to be modified, we only need to modify the access address of the configuration file.
  3. The third way: it doesn't need to download the server code. It accesses the server remotely through HTTP urlconnection, but it needs to generate the xml string and parse the results. Once the xml string parameter passed in is wrong, the response will fail or the resulting string parsing will fail.
  4. I recommend the second method, download the server code, and then write the address of the accessed server and create the corresponding interface to call the method. There is no need to write additional xml strings and parse strings.

đŸ˜Ŧ Advantages and disadvantages

🌈 advantage

  1. Through the third way of our client, we can know that I use XML format to encapsulate data, and XML is cross platform and does not need to be written in a specific language, so I am also cross platform.
  2. Through client access, we can know that the server can be remote or local, and we can call in different places through SOAP protocol.

🌩ī¸ shortcoming

Because I use XML format to encapsulate data, additional tags may need to be transmitted in the transmission process. However, if the tags are larger and larger, the performance of web service will be degraded.

đŸ”Ĩ Usage scenario

  1. Publish a service (internal / external), regardless of client type, language and performance. It is recommended to use WebService.

  2. The server has determined to use WebService. If the client cannot choose, it must use WebService.

💧 Not applicable scenario

  1. Considering the system performance, WebService is not recommended.

  2. It is not recommended to use WebService under isomorphic programs (interfaces between systems in a company), such as RMI (remote method call) for java, and there is no need to translate the data into XML.

🌸 summary

I believe all of you have a little understanding of how to use WebService, other concepts and some knowledge points. I'm not sure whether there are many people who use it. Here we only do introductory exercises. Of course, if we want to integrate it into the SpringBoot project, we can even integrate relevant dependencies to use WebService. For example, we can use SpringBoot and CXF to integrate WebService. Should we learn this technology? In fact, I think it depends on the requirements. If we need to use it, we can quickly understand it, use a small demo to get started quickly, and then use integrated CXF to integrate it into the project, so as to apply this technology to the actual project!

In fact, I haven't touched it personally. I'm just getting started because I need to call such a webService interface in the project, and now all web interfaces are basically based on http requests, so we can understand it, walk by and have a look to ensure that we don't suffer losses!!!

Let's cheer together! I am not talented. If there are any omissions and mistakes, I also welcome criticism and correction in the comments of talent leaders! Of course, if this article is sure to be of little help to you, please also give some praise and collection to the kind and lovely talent leaders. One key three times. Thank you very much!

Learn here, today's world is closed, good night! Although this article is over, I am still there and will never end. I will try to keep writing articles. The future is long. Why should we fear that cars are far away and horses are slow!

Thank you for seeing here! May you live up to your youth and have no regrets!

Topics: Java socket Back-end Network Protocol http