I used the Qingming Festival holiday to review the relevant content of Web Service and briefly summarized its working principle. For reference by friends in need and themselves in the future. If there is any inappropriate article, please ask your friends to give valuable suggestions to encourage each other.
In web services, we should first understand the meaning of related terms: WSDL, UDDI.... The introduction of related terms will not be repeated here, but the focus will be on principle.
In a web service, there are three roles: service provider, service requester and service intermediary. The relationship between the three is shown in Figure 1-1
Implementing a complete web service includes the following steps:
◆ Web service providers design and implement Web services, and publish the correct debugging of the Web service through the Web service intermediary and register it in the UDDI registration center; (Publish)
◆ The web service requester requests a specific service from the web service intermediary, and the intermediary queries the UDDI registration center based on the request to find a service that meets the request; (Discovery)
◆ The web service intermediary returns the Web service description information that meets the conditions to the web service requester. The description information is written in WSDL and can be read by various machines that support Web services; (Discovery)
◆ Use the description information (WSDL) returned from the Web service intermediary to generate corresponding SOAP messages and send them to the Web service provider to realize the call of the Web service; (binding)
◆ The web service provider executes the corresponding web service according to the SOAP message and returns the service result to the web service requester. (Binding)
Figure 1-1 Web service architecture
Note: The function of WSDL is a web service manual. The service requester generates the corresponding SOAP message based on this WSDL. After receiving the SOAP request message, the service provider binds the service.
The following code is the servlet configuration in web.xml
<!-- When formulating initialization parameters or custom URLs to servlet or JSP pages, you must first name the servlet or JSP page. The Servlet element is used to complete this task. --> <servlet> <servlet-name>UserService</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class> <!-- Mark whether the container loads this servlet when it is started (instand and call its init() method; the smaller the value of the positive number, the higher the priority of the servlet, the more it loads the application first when it is started --> <load-on-startup>1</load-on-startup> </servlet> <!-- The server generally provides a default URL for the servlet: http://host/webAppPrefix/servlet/ServletName. However, this URL is often changed so that the servlet can access initialization parameters or process relative URLs more easily. When changing the default URL, use the servlet-mapping element. --> <servlet-mapping> <servlet-name>UserService</servlet-name> <!-- Describes the URL relative to the root of the web application. The value of the url-pattern element must start with a slash (/). --> <url-pattern>/user</url-pattern> </servlet-mapping> The red code section is important and the corresponding servlet is loaded when the web container starts. The green section is the external interface of the service. Find the corresponding jax-ws.xml file (as shown below) <endpoint name="UserPort" implementation="cn.ujn.service.UserService" url-pattern="/user"> </endpoint>
It is then bound to the relevant corresponding implementation class cn.ujn.service.UserService. The SOAP request message body body sent by the client contains the method name and parameter information requested by the client.
The following is the soap message body encapsulated by the client (data transmission with the server in Json mode) (SOAP Rerquest Envelope):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ujn.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">- <soapenv:Body>- <q0:login> <arg0>{"username":"shq","password":"shq"}</arg0> </q0:login> </soapenv:Body> </soapenv:Envelope> The following is the SOAP1.1 protocol invoking the web service
/** * Calling the web service through the SOAP1.1 protocol* * text/xml This is based on the soap1.1 protocol* * @param wsdl WSDL path* @param method method method name* @param namespace namespace* @param headerParameters headerParameters header parameter* @param bodyParameters body parameter* @param isBodyParametersNS body parameter Whether there is a namespace for the body parameter* @return String * @throws Exception */ public static String invokeBySoap11(String wsdl, String method, String namespace, Map<String, String> headerParameters, Map<String, String> bodyParameters, boolean isBodyParametersNS) throws Exception { StringBuffer soapOfResult = null; // Remove ?wsdl, get the method list int length = wsdl.length(); wsdl = wsdl.substring(0, length - 5); //Create URL instance with string as parameters URL url = new URL(wsdl); //Create connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //Set the request method conn.setRequestMethod("POST"); //If you plan to use a URL connection for input, set the DoInput flag to true conn.setDoInput(true); //If you plan to use a URL connection for output, set the DoInput flag to true conn.setDoOutput(true); //Mainly set the attribute (KV) in the HttpURLConnection request header conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); //Get the input stream (relative to the client, use OutputStream) OutputStream out = conn.getOutputStream(); // Get the soap1.1 version message StringBuilder sb = new StringBuilder(); sb.append("<soap:Envelope xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//" "); sb.append("xmlns:ns0=/"" + namespace + "/""); sb.append(">"); //Assemble the message header if (headerParameters != null) { sb.append("<soap:Header>"); for (Entry<String, String> headerParameter : headerParameters .entrySet()) { sb.append("<ns0:"); sb.append(headerParameter.getKey()); sb.append(">"); sb.append(headerParameter.getValue()); sb.append("</ns0:"); sb.append(headerParameter.getKey()); sb.append(">"); } sb.append("</soap:Header>"); } //Assemble the message body sb.append("<soap:Body><ns0:"); sb.append(method); sb.append(">"); //Input parameter if (bodyParameters != null) { for (Entry<String, String> inputParameter : bodyParameters .entrySet()) { if (isBodyParametersNS) { sb.append("<ns0:"); sb.append(inputParameter.getKey()); sb.append(">"); sb.append(inputParameter.getValue()); sb.append("</ns0:"); sb.append(inputParameter.getKey()); sb.append(">"); } else { sb.append("<"); sb.append(inputParameter.getKey()); sb.append(">"); sb.append(inputParameter.getValue()); sb.append("</"); sb.append(inputParameter.getKey()); sb.append(">"); } } } sb.append("</ns0:"); sb.append(method); sb.append("></soap:Body></soap:Envelope>"); //Test System.out.println(sb.toString()); //Write SOAP messages (relative to the client, out.write() is used) out.write(sb.toString().getBytes()); //Get the corresponding int code on the server side = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); byte[] b = new byte[1024]; int len = 0; soapOfResult = new StringBuffer(); //Read a certain number of bytes from the input stream and store them in the buffer array b. Returns the actual number of bytes read as an integer //If there are no bytes available because the stream is at the end of the file, the value is -1; while ((len = is.read(b)) != -1) { //Converts the byte array to a string using the named charset. String s = new String(b, 0, len, "UTF-8"); soapOfResult.append(s); } } conn.disconnect(); return soapOfResult == null ? null : soapOfResult.toString(); } Note: The client is blocked after sending the SOAP request message. Until the server returns the status code.
The following is the server response (SOAP Response Envelope):
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">-<S:Body>-<ns2:loginResponse xmlns:ns2="http://ujn.cn/"> <return>1</return></ns2:loginResponse> </S:Body></S:Envelope>
After receiving the Json data sent by the server, the client will perform corresponding parsing operations. as follows:
// parse the Soap protocol (DOM parsing can only be used to parse XML document types, while SOAP messages are in XML data format) Document doc = XmlUtil.string2Doc(result); Element ele = (Element) doc.getElementsByTagName("return").item(0); The string2Doc() method used in the method is as follows: public static Document string2Doc(String str) { // parse the XML document into a DOM tree DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = null; DocumentBuilder build; if (str == null || str.equals("")) { return null; } try { InputStream bais = new ByteArrayInputStream(str.getBytes("UTF-8")); build = factory.newDocumentBuilder(); //Parse the content of the given InputStream as an XML document and return a new DOM Document object. document = build.parse(bais); } catch (Exception e) { e.printStackTrace(); } return document; } According to the return result, the client will perform corresponding processing.
The above is the basic working principle of web services.
Thank you for reading, I hope it can help you. Thank you for your support for this site!