English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Introduction to the Running Principle of Web Service

     Taking advantage of the Tomb Sweeping Day holiday, I reviewed the relevant content of Web Service and briefly summarized its working principle for reference by friends in need and myself in the future. If there are any inappropriate places in the article, please kindly put forward valuable suggestions for mutual encouragement.

      In Web services, we should first understand the meanings of relevant terms: WSDL, UDDI, etc. The introduction of relevant terms will not be elaborated here, focusing on the principles.
In Web services, there are three roles: service provider, service requestor, and service broker, and their relationships are shown in the figure1-1Shown

    Implementing a complete Web service includes the following steps:

   ◆ The Web service provider designs and implements the Web service, publishes the correctly debugged Web service through the Web service broker, and registers it in the UDDI registry center; (Publishing)

   ◆ The Web service requestor requests a specific service from the Web service broker, and the broker queries the UDDI registry center based on the request to find a service that meets the request for the requestor; (Discovery)

   ◆ The Web service broker returns the descriptive information of the Web service that meets the conditions to the Web service requestor, which is written in WSDL and can be read by various machines that support Web services; (Discovery)

   ◆ Generate the corresponding SOAP message using the descriptive information returned from the Web service broker (WSDL) and send it to the Web service provider to call the Web service; (Binding)

   ◆ The Web service provider performs the corresponding Web service based on the SOAP message and returns the service result to the Web service requestor. (Binding)

  

Figure1-1 Architecture of Web service

     Note: The role of WSDL is to act as a Web service specification. The service requestor generates the corresponding SOAP message based on this WSDL, and the service provider binds the service after receiving the SOAP request message.

     The following code is the servlet configuration in web.xml

  <!-- When defining initialization parameters or custom URLs for servlets or JSP pages, it is necessary to name the servlet or JSP page first. The servlet element is used to accomplish this task. -->
  <servlet>
  <servlet-name>UserService</servlet-name>
  <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
  <!-- tag whether the container loads this servlet at startup (instantiates and calls its init() method; the smaller the positive value, the higher the priority of the servlet, and it will be loaded earlier when the application starts -->
  <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- The server usually provides a default URL for servlets: http://host/webAppPrefix/servlet/ServletName.
   However, it is often changed so that the servlet can access initialization parameters or handle relative URLs more easily. When changing the default URL, use the servlet-mapping element. -->
  <servlet-mapping>
   <servlet-name>UserService</servlet-name>
   <!-- It describes the URL relative to the root directory of the web application. url-The value of the pattern element must start with a slash (/)starting. -->
   <url-pattern>/user</url-pattern>
  </servlet-mapping>
  The red code part is very important and will load the corresponding servlet when the web container starts. The green part 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>

    Then it binds to the corresponding implementation class cn.ujn.service.UserService. The SOAP request message 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 (transmitted to the server in JSON format) (SOAP Request 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 SOAP1.1Protocol to call web services

/** 
* Through SOAP1.1Protocol to call web services 
* 
* text/xml This is based on soap1.1Protocol 
* 
* @param wsdl WSDL path 
* @param method Method name 
* @param namespace Namespace 
* @param headerParameters Header parameters 
* @param bodyParameters Body parameters 
* @param isBodyParametersNS Whether the body parameters have a namespace 
* @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 &63;wsdl, get the list of methods 
int length = wsdl.length(); 
wsdl = wsdl.substring(0, length - 5; 
//Create a URL instance with a string as a parameter 
URL url = new URL(wsdl); 
//Create a connection 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
//Set the request method 
conn.setRequestMethod("POST"); 
//If you plan to use URL connection for input, set the DoInput flag to true 
conn.setDoInput(true); 
//If you plan to use URL connection for output, set the DoInput flag to true 
conn.setDoOutput(true); 
//It is mainly used to set the properties in the HttpURLConnection request header (K-V) 
conn.setRequestProperty("Content-Type",-Type/xml;charset=utf-8-8"); 
//Get input stream (relative to the client, it uses OutputStream) 
OutputStream out = conn.getOutputStream(); 
// Get soap1.1Version 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 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 message body 
sb.append("<soap:Body><ns0:"); 
sb.append(method); 
sb.append(>"); 
// Input parameters 
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 case 
System.out.println(sb.toString()); 
//写入SOAP消息(相对于客户端来说,使用的是out.write()) 
out.write(sb.toString().getBytes()); 
//获取服务器端的相应 
int code = conn.getResponseCode(); 
if (code == 200) { 
InputStream is = conn.getInputStream(); 
byte[] b = new byte[1024 
int len = 0; 
soapOfResult = new StringBuffer(); 
//Reads a certain number of bytes from the input stream and stores them in the buffer array b. Returns the actual number of bytes read as an integer 
//If there are no available bytes because the stream is at the end of the file, the return value -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: After the client sends the SOAP request message, it is in a blocking state until the server returns the status code.

    The following is the server's 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 the client receives the Json data sent by the server, it will perform the corresponding parsing operation. For example:

// 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 string used in the method2Doc() method body 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"));-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; 
} 

    The client performs the corresponding processing based on the returned results.

    The above is the basic working principle of web services.

    Thank you for reading, I hope it can help everyone, thank you for your support to this site!

You May Also Like