This paper is participating in theNetwork protocols must be known and must be known”Essay campaign
The vast sea of millions, thank you for this second you see here. I hope my article is helpful to you!
May you keep your love and go to the mountains and seas in the coming days!
👀 preface
Some time ago, webService was needed to call other system API interfaces of the company, but the request method was different from THE HTTP request I was familiar with. It was based on SOAP protocol to transmit XML data format, and the request parameters were extremely complex, requiring encapsulation of multi-layer XML data format. And I don’t know what language their API is, or even what platform they exist on.
So how does this differ from the httpapi interface that we’ve seen so often?
- Different protocols: HTTPService is based on HTTP, while WebService is based on SOAP.
- Different data processing efficiencies: HTTPService is more efficient and transfers strings, while WebService is packaged as more complex objects to handle more complex data types.
- Cross-domain processing: HttpService does not handle cross-domain processing. If you call a service from another application, you use webService, as I am calling a service from another system.
😀 overview
😆 introduce
Webservices are mainly software services provided on the Web through THE SOAP protocol, described using WSDL documents and registered through UDDI. WebService is a remote call technology across programming languages and operating system platforms, which 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 WebService specification can exchange data with each other, regardless of the language, platform, or internal protocol they use.
So, if you want to use different languages, different platforms, different places, want to carry out data transmission, self-recommendation, choose WebService is right!
🔄 multi-dimensional understanding
- On the surface, A WebService is an application program that exposes an API to the outside world that can be called through the Web, that is, the application program can be called through the Web programmatically. The application that invokes the WebService is called the client, and the application that provides the WebService is called the server.
- From the inside, WebService is not a technology, more like a new platform built on interoperable distributed applications, a platform, a set of standards, a specification. It defines how applications can be interoperable on the Web, and you can write Web Services in any language you like, on any platform you like, as long as we can query and access those services through the WebService standard.
👩👧👦 Three good brothers
Often associated with three element brothers: UDDI, WSDL, and SOAP
-
UDDI: UDDI is a technology for describing, discovering, and integrating Web services. It is an important part of the Web Service protocol stack. With UDDI, businesses can dynamically locate and consume Web services based on their own needs, or publish their Web services dynamically to a UDDI registry for other users to use. UDDI utilizes SOAP messaging mechanisms (standard XML/HTTP) to publish, edit, browse, and find registry information. It encapsulates various types of data in XML format and sends it to the registry or is returned by the registry as needed.
-
WSDL: Is the XML format used to describe Web service publishing. Is an XML-based (a subset of standard Common Markup Language) language that describes webServices and their functions, parameters, and return values in a formal document description provided in machine-readable form. Because it is xmL-based, WSDL is machine-readable as well as human-readable.
-
SOAP (Simple Object Access Protocol) is a lightweight, simple protocol based on a subset of the XML standard Common Markup Language. It mainly consists of Http protocol and XML data format. When a WebService sends a request and receives a result over HTTP, the request content and result content are encapsulated in XML format, and some SPECIFIC HTTP headers are added to illustrate the content format of HTTP messages. These specific HTTP headers and XML content formats are SOAP protocols. SOAP provides a standard RPC(Remote Invocation Technology) method to invoke a WebService.
😎 The benefits of choice
- Cross-platform invocation.
- Call across languages.
- Remote call.
😜 to get started
No more words, see too much theory is not as good as their own small demo measured down. So Let’s GO!
Make a weather system demo. The client sends the name of the city and the server responds with the weather.
📖 Create an empty project
Create an empty project weatherServer, I use IDEA version 2020.3. Of course, I went into more detail at the beginning
🍉 Implements the publishing server
1. Create the weatherServerTest module
The creation process is basically similar. If you want to choose to use me, THEN I would suggest that you create a server first, so that others can access, or use someone else’s server is OK. Here will complete the creation of a server module, the subsequent creation of the client module is basically similar. Here we can choose either a Maven project or a regular Java project of our own. The JDK is the popular JDK8.
The final empty module server is as follows:
2. Provide weather services
The next step is to develop the server-side code. Provide simple city weather service.
-
Define a weather service interface, IWeatherService
The code is as follows:
package com.ws.service; public interface IWeatherSerice { /** * Get the weather from the city name *@paramCity city *@returnThe weather is * / public String queryWeather(String city); } Copy the code
-
Write the corresponding interface implementation class WeatherServiceImpl
The corresponding code is as follows:
package com.ws.service.impl; import com.ws.service.IWeatherSerice; import javax.jws.WebService; @WebService // Use this annotation to indicate that the current class is a service class must be added, otherwise an error will be reported when starting the service. public class WeatherServiceImpl implements IWeatherSerice { @Override public String queryWeather(String city) { // Return directly to the corresponding city and sunny days!! return city + The weather is: sunny!; }}Copy the code
-
Create a WeatherServerDemo class to publish the service.
The corresponding code is 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 --> address provided for access ** implementor: service class --> implementation of the interface provided for access */ Endpoint.publish("http://localhost:8086/weatherServer".new WeatherServiceImpl()); System.out.println("Service published successfully"); }}Copy the code
-
Run the main method to start the service:
As you can see from the console, it does not close after running and shows that the service has been published successfully. Next, check out our service online.
3. Access services
Access the address of the access just provided plus? WSDL, such as: http://localhost:8086/weatherServer? wsdl
So what about this WSDL document? No, let me show you a few 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 Services. It also describes the methods, inputs, and outputs of Web Services.
- : describes the operations that a WebService can perform. Binding refers to a portType
- : describes the methods published in the service, including parameters, return values, and so on.
- : defines the data types used in WebService
To access a detailed parameters page: http://localhost:8086/weatherServer? xsd=1
🍊 Several ways to implement client access
1. Create the weatherClientTest client module
Structure:
2. Generate corresponding client code
Why do you need to download the client code? First of all, the first two methods need to use the interface of the server code, and then if you are the remote server, you can’t access it.
Here is the JDK’s built-in command: wsimport
Wsimport.exe is in the JAVA_HOME\bin directory. The common parameters are: -d< directory > -. Class files will be generated. Default parameter. -s< directory > -.java files will be generated. -p< generated new package name > - To generate the class, in the specified package wsimport -s./ HTTP://localhost:8086/weatherServer? wsdl
Copy the code
Generation steps:
-
Go to the Java directory of the client module SRC
-
In the directory, enter the command line mode, and then input the wsimport – s. / http://localhost:8086/weatherServer? WSDL, download the server-side code you just started. Note: This step must ensure that the server is enabled and accessible.
- The structure of the final generated code in IDEA is:
The code obtained here corresponds to the name of the WSDL document. Of course, if you want to change the package name, you can use the -p parameter.
3. Client access mode 1
The first way: with the resulting code, the service is called.
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 a service view
WeatherServiceImplService weatherServiceImplService = new WeatherServiceImplService();
// 2. Get the service implementation class
WeatherServiceImpl weatherService = weatherServiceImplService.getPort(WeatherServiceImpl.class);
// 3. Call the interface's methods
String result = weatherService.queryWeather("Guangzhou");
// 4. Return the result of remote access --> result = Guangzhou weather: sunny!
System.out.println("result = "+ result); }}Copy the code
When we run it, the results are as expected:
4. Client access mode 2
The drawback of this step should be clear: we have fixed a service address and may need to regenerate the code if we want to change the service address.
So we write out the service address, 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 IP address of the access server
URL url = new URL("http://localhost:8086/weatherServer? wsdl");
/* 2. Set the service name and namespace namespaceURI: WSDL namespace (targetNamespace) localPart: is the service view name (service name value) */
QName qName = new QName("http://impl.service.ws.com/"."WeatherServiceImplService");
// 3. Generate a service view
Service service = Service.create(url, qName);
// 4. Get the service view implementation class --> WeatherServiceImpl
WeatherServiceImpl weatherServiceImpl = service.getPort(WeatherServiceImpl.class);
// 5. Call the interface method and get the result! --> result = Shenzhen weather: sunny!
String result = weatherServiceImpl.queryWeather("Shenzhen");
System.out.println("result = "+ result); }}Copy the code
Where are these corresponding parameters in the WSDL? Let me show you:
This second way is more commonly used way, the first recommendation!
5. Client access mode 3
If you do not need to download the server code, use HTTPURLConnection to access the server. But here the code is relatively long, and you need to define your own XML string and parse string.
-
Add a dom4J dependency package to the POM.xml file
<dependencies> <dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.11.</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.11.</version> </dependency> </dependencies> Copy the code
The structure is as follows:
-
Create the corresponding test demo with the following structure:
The code is as follows: you can copy to IDEA for a closer look.
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 IP address of the access server 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 argument, --> POST must be capitalized, otherwise an exception is thrown connection.setRequestMethod("POST"); // This is text/ XML, not text/ HTML connection.setRequestProperty("content-Type"."text/xml; charset=utf-8"); // 4. Set the input and output. The default value is false connection.setDoOutput(true); connection.setDoInput(true); // 5. Organize SOAP data and send requests String soapXml = getXmlString("Foshan"); System.out.println("soapXml = " + soapXml); // 6. Write data to the output stream DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.write(soapXml.getBytes("utf-8")); dos.flush(); // 7. Check whether the remote access succeeds. If the response code is 200, the remote access succeeds 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()) { buffer.append(scanner.nextLine()); } scanner.close(); // Get an 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()); //" //" Selects the node named item from the node at any location. Node node = document.selectSingleNode("//return"); return node.getText(); } catch (DocumentException e) { e.printStackTrace(); } return null; } private static String getXmlString(String string) { String xml = " " + "<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>\""; returnxml; }}Copy the code
-
Results obtained:
As you can see, you can get the corresponding result.
6. Three ways to compare
- The first method: although the code is relatively simple, but the coupling degree is high, only applicable to the current download server address. Generally when we start the server, the interface methods, parameters and so on do not change much. But if the address changes, you need to download the server code again.
- 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 the CONFIGURATION file such as XML file. Once you need to modify the configuration file, you only need to modify the access address.
- The third way: it doesn’t need to download the server code and access the server remotely via HTTPURLConnection, but it needs to generate the XML string itself and then parse the result itself. If the wrong XML string argument is passed in, the response fails, or the resulting string fails to be parsed.
- I recommend the second way, download the server code, and then write the address of the access 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 😬
🌈 advantages
- Through our client’s third way, we can see that I am using XML format to encapsulate the data, and XML is cross-platform, and does not need to be written in a specific language, so I am also cross-platform.
- Through the way of client access, we can know that the server can be in remote, can be in local, we can achieve remote invocation through SOAP protocol.
🌩 ️ shortcomings
Since I use XML format to encapsulate the data, I may need to transfer additional tags during transmission. However, if the tags become larger, the performance of WebService will degrade.
🔥 Application Scenario
-
Publish a service (internal or external) regardless of client type, language, or performance. WebService is recommended.
-
If the server is determined to use WebService, the client must use WebService.
💧 Does not apply to scenarios
-
WebService is not recommended for system performance.
-
Webservices are not recommended for homogeneous programs (interfaces between systems within a company), such as Java with RMI(remote method calls), which do not require data translated into XML.
🌸 summary
If we want to integrate into the SpringBoot project, we can even integrate dependencies to use the webService. For example, we can use SpringBoot to integrate WebService using CXF. So should we learn this technique? In fact, I think according to the requirements, if we need to use it, we can quickly understand it, use a small demo to start quickly, and then use integrated CXF to integrate into the project, so as to achieve the application of this technology to the actual project!
I personally did not contact, because the project needs to call such webService interface requirements, so I also just started, and now the web interface is basically based on HTTP requests to do, so we can understand when understand, pass by, take a look, guarantee not to lose!!
Let’s refuel together, too! I am not just, if there is any missing, wrong place, also welcome you to criticize in the comments of talent leaders! Of course, if this article is sure to help you a little, please kindly and lovely talent leaders to give a thumb-up, favorites, one key three even, thank you very much!
Here, the world is closed for today, good night! Although this article is over, I am still here, never finished. I will try to keep writing articles. The coming days are long, why fear the car yao ma slow!
Thank you all for seeing this! May you live up to your youth and have no regrets!