A detailed introduction to the principle of Web Service operation _java

Source: Internet
Author: User
Tags soap xmlns stringbuffer wsdl

The use of Qingming holiday, a review of the Web service related content, the principle of its work is briefly summarized. For the needs of friends and their future reference. If there is any improper article, please friends to put forward valuable suggestions, in order to encourage mutual encouragement.

Web services, we should first understand the relevant terminology meaning: WSDL, UDDI .... The relevant terminology of the introduction here no longer repeat, the emphasis on the principle.
In Web services, there are three roles: service providers, service requesters, and service intermediaries, and the relationships between the three are as shown in Figure 1-1

Implementing a complete Web service consists of the following steps:

The Web service provider designs and implements Web services and publishes the properly debugged Web services through Web service intermediaries and registers with the UDDI registry;

The Web service requester requests a specific service from the Web service mediator, the broker queries the UDDI registry based on the request, and the requester finds the service that satisfies the request;

The Web Service Broker returns the Web Service description information to the Web service requester that satisfies the condition, which is written in WSDL and can be read by various Web services-enabled machines;

Generates a corresponding SOAP message using the descriptive information (WSDL) returned from the Web Service Broker, sent to the Web service provider to implement the invocation of the Web service;

The Web service provider executes the corresponding Web service by 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 specification. The service requester 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

  <!--you must first name a servlet or JSP page when you make initialization parameters or custom URLs to a servlet or JSP page. The servlet element is used to accomplish this task. --> <servlet> <servlet-name>UserService</servlet-name> <servlet-class> The com.sun.xml.ws.transport.http.servlet.wsservlet</servlet-class> <!--tag container loads this servlet at boot time ( Instantiating and calling its init () method; The smaller the value of a positive number, the higher the priority of the servlet, and the more loaded--> <load-on-startup>1</load-on-startup> </when the application starts
   Servlet> <!--servers typically provide a default url:http://host/webappprefix/servlet/servletname for the servlet. However, this URL is often changed so that the servlet can access the initialization parameters or more easily handle relative URLs. The servlet-mapping element is used when changing the default URL. --> <servlet-mapping> <servlet-name>UserService</servlet-name> <!--describes the URL of the root directory relative to the Web application. The value of the Url-pattern element must start with a slash (/). The--> <url-pattern>/user</url-pattern> </servlet-mapping> Red Code section is important to load the corresponding servlet when the Web container is started. The green section is the external interface for the service. To find the appropriate Jax-ws.xml file (shown below) <endpoint name= "Userport" implementation= "Cn.ujn.service.UserService" url-pattern= "/ User "> </endpoint>

 

It is then bound to the relevant implementation class Cn.ujn.service.UserService. The client sends a SOAP request message message body containing the method name and parameter information requested by the client.

The following is a client-encapsulated SOAP message body (data transfer in JSON to the server) (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 calls the Web service for the SOAP1.1 protocol

/** * Invoke Web service via SOAP1.1 protocol * * Text/xml This is based on the soap1.1 protocol * * @param wsdl wsdl Path * @param method Name * @param namespace name 
Space * @param headerparameters header parameter * @param bodyparameters body parameter * @param Isbodyparametersns body parameter has 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 the WSDL, get the method list int length = Wsdl.length (); 
wsdl = wsdl.substring (0, length-5); 
Creates a URL instance url url = new URL (WSDL) with a string as a parameter; 
Create connection HttpURLConnection conn = (httpurlconnection) url.openconnection (); 
Set the request mode Conn.setrequestmethod ("POST"); 
If you intend to use a URL connection for input, set the DOINPUT flag to True Conn.setdoinput (true); 
If you intend to use a URL connection for output, set the DOINPUT flag to True Conn.setdooutput (true); The main is to set the attributes (K-V) Conn.setrequestproperty in the HttpURLConnection request header ("Content-type", "text/xml;chArset=utf-8 "); 
Gets the input stream (OutputStream is used relative to the client) OutputStream out = Conn.getoutputstream (); 
Gets 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 (">"); 
Assembly message Header if (headerparameters!= null) {sb.append ("<soap:Header>"); 
For (entry<string, string> headerparameter:headerparameters. EntrySet ()) {Sb.append ("&LT;NS0:"); 
Sb.append (Headerparameter.getkey ()); 
Sb.append (">"); 
Sb.append (Headerparameter.getvalue ()); 
Sb.append ("&LT;/NS0:"); 
Sb.append (Headerparameter.getkey ()); 
Sb.append (">"); 
} sb.append ("</soap:Header>"); 
}//Assembly message body Sb.append ("&LT;SOAP:BODY&GT;&LT;NS0:"); 
Sb.append (method); 
Sb.append (">"); Input parameter if (bodyparameters!= null) {for (entry<string, string> InputparamEter:bodyparameters. EntrySet ()) {if (Isbodyparametersns) {sb.append ("&LT;NS0:"); 
Sb.append (Inputparameter.getkey ()); 
Sb.append (">"); 
Sb.append (Inputparameter.getvalue ()); 
Sb.append ("&LT;/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 ("&LT;/NS0:"); 
Sb.append (method); 
Sb.append ("></soap:Body></soap:Envelope>"); 
Test with System.out.println (Sb.tostring ()); 
Writes a SOAP message (Out.write ()) Out.write (Sb.tostring ()) is used relative to the client (). GetBytes ()); 
Gets the corresponding int code = Conn.getresponsecode () on the server side; 
if (code = =) {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 buffer array B. Returns the number of bytes actually read as an integer//if the stream is at the end of the file and no bytes are available, the value -1 is returned; 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 sends a SOAP request message and is in a blocking state. Until the service side returns the status code.

The following is a server-side 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>

The client receives the JSON data sent from the server and then parses the corresponding parsing operation. As follows:

Parsing the SOAP protocol (DOM parsing can only be used to parse XML document types, and 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) { 
//parsing an 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 results of the return, the client will be processed accordingly.

These are the basics of how Web services work.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.