WebService learning and sorting (1) -- three client call methods, webservice Client

Source: Internet
Author: User
Tags webservice annotation email account

WebService learning and sorting (1) -- three client call methods, webservice Client
1. Basic functions of WebService 1.1

1. WebService is a remote call between two systems to enable data interaction between the two systems, such as applications:

Weather forecast service, bank ATM withdrawal, use email account to log on to various websites, etc.

2. Inter-WebService calls are cross-language calls. Java,. Net, and php send Http requests in XML format.

3. There are some free WebService services on webxml.com.cn. You can check them out.

1.2 application Basics

4. Basic concepts:

(1) Understanding services:

Today's applications are becoming more and more complex, and even a single application alone cannot do all the work. Let alone use only one language. Therefore, you need to access services written by others to obtain data of interest.

When writing an application to query a database, I did not consider why I can return the query results to the upper-layer application. I even thought that this is what the database should do, this is the result of communication between the database and another application through the TCP/IP protocol. The database itself does not know what kind of application is at the upper layer and what language it uses, it only knows that it has received one protocol, which is the standard protocol for querying SQL92.

Currently, cloud computing and cloud scanning and removal are a kind of service. The popular saying is SOA (a service-oriented framework ).

Since the database can provide services to other external applications based on certain standards, and does not care about the language in which the other party uses, why cannot we implement cross-platform and cross-language services?

As long as the code written in Java can be called by any language, we can implement cross-platform and cross-language services! --- WebService

Therefore, WebService, as its name implies, is a Web-based service. It uses the Web (HTTP) method to receive and respond to a request from an external system. To achieve remote calls.

We can call the Web Service for querying weather information on the Internet and embed it into our program (C/S or B/S program, when a user sees weather information from our outlets, he will think that we provide him with a lot of information services, but we have not done anything, it's just a simple call of a piece of code on the server.

Learning about WebService can publish your service (a piece of code) to the Internet for others to call, or call the WebService published on another machine, just like using your own code.

(2) Basic Concept: XML

XML Extensible Markup Language-Extensible Markup Language

XML, used to transmit formatted data, is the basis of Web Services.

Namespace-namespace.

(3) Basic Concept: WSDL

WSDL-WebService Description Language-Web Service Description Language.

Describe the service address in XML format. Address location

Describes the methods provided by the Service in XML format-how to call them. Operation

(4) Basic Concept: SOAP

SOAP-Simple Object Access Protocol (Simple Object Access Protocol)

As an XML-based protocol, SOAP is used to transmit data online.

SOAP = + XML data based on HTTP.

SOAP is based on HTTP.

The composition of SOAP is as follows:

Envelope-required part. It appears as the root element of XML.

Headers-optional.

Body-required. The body section contains the method of the server to be executed. And the data sent to the server.

Transmitted data format:

<Envelope>

<Header> </Header>

<Body>

<Method Name>

Method Parameters

</Method Name>

</Body>

</Envelope>

(5) Request example:

The following HTTP request is sent, but the difference is that XML data is sent to the server!

Note: (1) because data is sent over HTTP, the HTTP protocol must be followed first.

(2) The XML part is the SOAP protocol and must contain the Envelope and Body elements.

(6) response example:

1.3 Application description

1. WebService performs remote call through HTTP protocol

(1) WebService only transmits data through http post instead of GET; -- handshake, WSDL-get, (based on the soap protocol, the format of transmitted data is XML)

The contentType of normal http post is

Application/x-www-form-urlencoded

The contentType of WebService is-that is, the SOAP protocol is sent based on Http.

Text/xml is based on the soap1.1 protocol.

Application/soap + xml is based on the soap1.2 protocol.

(2) WebService limits the data transmission format. The data used by WebService is in XML format. Currently, the standard WebService mainly adopts the SOAP protocol in data format. The SOAP protocol is actually a text protocol based on XML encoding specifications.

(3) SOAP-Simple Object Access protocol. Is a protocol running on the basis of the HTTP protocol. In fact, the HTTP protocol is used to transmit XML files and thus the SOAP protocol.

(4) SOAP1.1 and SOAP1.2 have different namespaces. You can view the class

Javax. xml. ws. soap. SOAPBinding to view Constants

By default, Jdk1.6 only supports soap1.1

That is: @ BindingType (value = javax. xml. ws. soap. SOAPBinding. SOAP11HTTP_BINDING)

1.4 difference and connection between WebService and Web

WebService can be viewed as an application on a Web server. In other words, a Web server is a required container for running WebService. This is their difference and connection.

 

1.5 WebService features

WebService accepts client requests through http post (if the data transmission format is XML based on the soap protocol), it can only be POST, because the GET method has no request body.

Generally, XML data is transmitted between the WebService and the client using the SOAP protocol.

It is designed for cross-platform or cross-language use.

(1) SOAP1.2 Note: After SOAP12 is used, neither wsimport nor Eclipse nor WSExplorer can be used normally. You must use the wsdl2java tool provided by cxf to generate local code.

(2) It is best for the client to send a 1.1 request, while the server is better to use a 1.2 higher version.

2 Application Example 2.1 publish the WebService (use a version later than Jdk1.6.0 _ 21)

1. Use JDK 1.6.0 _ 21 to publish a WebService (using annotation)

Classes related to Web services are all located in the javax. jws. * package.

Main categories include:

@ WebService-it is an annotation and is used on the class to specify to publish this class into a ws.

Endpoint-This class is an Endpoint service class. Its publish method is used to bind an annotation object added with @ WebService to an address port.

(1) A simple Java project, HelloService

① Create the following package structure:

 

② Create a class HelloService. java with the main method, and add the @ WebService annotation to the class.

Use the publish method of the EndPoint class in the class:

At least one method can be released: (The method cannot be static or non-final). Only such method can be released.

@ WebService

Public class HelloService {

Public String sayHello (String name ){

System. out. println ("sayHello Called ...");

Return "hello" + name;

}

Public static void main (String [] args ){

// Parameter 1: Address of the bound service

// Parameter 2: The instance that provides the service

Endpoint. publish ("http: // 124.205.244.130: 5678/hello", new HelloService ());

System. out. println ("server ready ...");

}

}

Use EndPoint. the publish () method will open a new thread, so it will not affect the running of the main thread. Therefore, when running the main method, the console can still see the output: server ready.

③ After the service is successfully published, call it on the client:

After starting the service, enter the bound service address + "? To view the Service Specification. The wsdl-WebService Description Language describes the "Manual" of WebService in the form of an XML file. With the instructions, we can know how to use or call this service.

④ Use wsimport-s. http: // 124.205.244.130: 5678/hello? Wsdl

The client code is generated. (Including the. class file and. java file)

Note: all classes and methods generated on the server are generated instead of downloaded.

⑤ Create a new Java project HelloService_Client as the client, package the. java file together in this project, and call:

Public class App {

Public static void main (String [] args ){

/**

* Wsdl: <service name = "HelloServiceService">

*/

HelloServiceService has = new HelloServiceService ();

/**

* Wsdl: <port name = "HelloServicePort" bind = "tns: HelloServicePortBinding">

*/

HelloService soap = has. getHelloServicePort ();

String str = soap. sayHello ("zhangan ");

System. out. println (str );

}

}

It can be seen on the console of the Client: hello zhangsan, complete the client call

Note:

Wsimport comes with jdk and can generate client call code according to the wsdl document. Of course, no matter what language the WebService on the server is written in, Java code will be generated on the client. What the server uses to write is not important.

Wsimport.exe is located in the JAVA_HOME \ bin directory.

Common parameters:

-D <directory>-The. class file will be generated. Default parameter.

-S <directory>-The. java file will be generated.

-P <new package name generated>-place the generated class under the specified package and customize the package structure.

(Wsdlurl)-http: // server: port/service? Required parameter.

Example:

C:/> wsimport-s. http: // 192.168.0.100/one? Wsdl

C:/> wsimport-s.-p com. sitech. web

Http: // 192.168.0.100/one? Wsdl

Note:-s cannot be separated.-s is followed by a small dot to specify the directory generated by the source code. Point is the current directory.

If the-s parameter is used, two codes are generated in the directory, one of which is. class code. One copy is. java code.

. Class code, which can be used after packaging .. Java code can be directly copied to our project for running.

 

2. Use wsimport to generate local code and call web Services on the network, such as the mobile phone number attribution service.

Go to xml.com.cn and find the wsdl of the mobile phone number Home Service:

Copy and use the wsimport command to copy the generated java code to the MobileService project.

 

Call on the client:

Public static void main (String [] args ){

MobileCodeWS mc = new MobileCodeWS ();

MobileCodeWSSoap soap = mc. getMobileCodeWSSoap ();

String str = soap. getMobileCodeInfo ("13011286707", null );

System. out. println (str );

}

Client console printing:

Beijing Unicom

Note: The proxy class is used on both the WebService client and the server. Therefore, the client accesses the server as a proxy object, and the proxy object is used when the client interacts with the server.

3. When wsimpot is used to generate the client call code, if the wsdl uses a local file, if the local wsdl file is deleted after the client code is generated, during the call process, the local file cannot be found. In this case, you only need to replace the code that references the local wsdl file with the url address of the wsdl.

2.2 how the client calls WebService

Use wsimport to generate client code

Call through client Programming

Call through ajax (js + XML)

Call through URLConnection

2.2.1 use wsimport to generate client code

See 2.1

2.2.2 call through client Programming

(1) Use the javax. xml. ws. Service class to access web services

(2) key services

Method create-the user creates a Service object and provides the wsdlurl and Service name.

GetPort-is used to specify the namespace, portName, and interface model.

A class identical to the server interface is required on the client. (Still generated using tools. But only one interface is required. And needs to be modified. If a complex data type such as POJO is returned, you also need to put the POJO in the project ).

App. class file:

Service s =

Service. create (new URL ("http: // 192.168.1.108: 5678/hello? Wsdl "),

New QName (targetNamespace, serviceName)

);

HelloService hs = s. getPort (portName, serviceEndpointInterface );

(Note: portName = new QName (targetNamespace, portName ))

String str = hs. sayHello ("Lisi", 10 );

System. out. println (str); // print hello Lisi

Note: The key class QName is called the fully Qualified Name, that is, the abbreviation of Qualified Name.

The QName value includes the namespace URI, local part, and prefix.

Client programming is not commonly used.

 

2.2.3 call through Ajax (js + XML)

(1) Write a page and send an Ajax request. The requested URL is the service address. The request method is POST. In addition, you must set the request header and manually construct the Request body.

<Body>

<Input type = "text" id = "msg"/>

<Input type = "button" onclick = "sendAjaxWS ();" value = "Call webservice through ajax"/>

</Body>

<Head>

<Title> call webservice through ajax </title>

<Script>

Var xhr;

Function sendAjaxWS (){

Xhr = new ActiveXObject ("Microsoft. XMLHTTP ");

// Specify the ws request address

Var wsUrl = "http: // 192.168.1.108: 5678/hello ";

// Manually construct the Request body

Var requestBody = '<soapenv: Envelope xmlns: soapenv = "http://schemas.xmlsoap.org/soap/envelope/"' + 'xmlns: q0 = "http://service.itcast.cn/" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" '+

'Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"> '+

'<Soapenv: Body> <q0: sayHello> <arg0>' +

Document. getElementById ("msg "). value + '</arg0> <arg1> 10 </arg1> </q0: sayHello> </soapenv: Body> </soapenv: Envelope> ';

// Open the connection

Xhr. open ("POST", wsUrl, true );

// Reset the request header xhr. setRequestHeader ("content-type", "text/xml; charset = utf8 ");

// Set the callback function

Xhr. onreadystatechange = _ back;

// Send the request

Xhr. send (requestBody );

}

// Define the callback function

Function _ back (){

If (xhr. readyState = 4 ){

If (xhr. status = 200 ){

Var ret = xhr. responseXML;

// Parse xml

Var eles = ret. getElementsByTagName ("return") [0];

Alert (eles. text );

}

}

}

</Script>

</Head>

The use of ajax-js to call web Services is different from that of java code. Therefore, you must have a good understanding of SOAP files.

Generally, ajax is called only after the following information is known:

Obtain the soap Text of the request.

Get the soap text of the response (response.

The request file and response text format are generally released along with the release of the web service.

We can use WSExplorer to obtain the above two paragraphs.

2.2.4 called through URLConnection

1. Specify the request address of the WebService:

String wsUrl = "http: // 124.205.244.130: 5678/hello ";

2. Create a URL: URL url = new URL (wsUrl );

3. Establish a connection and convert the strong connection to an Http Connection

URLConnection conn = url. openConnection ();

HttpURLConnection con = (HttpURLConnection) conn;

4. Set the Request Method and request header:

Con. setDoInput (true); // whether an input parameter exists

Con. setDoOutput (true); // whether an output parameter exists

Con. setRequestMethod ("POST"); // you can specify the request method.

Con. setRequestProperty ("content-type", "text/xml; charset = UTF-8 ");

5, // manually construct the Request body

String requestBody = "<soapenv: Envelope xmlns: soapenv = \" http://schemas.xmlsoap.org/soap/envelope /\""

+ "Xmlns: q0 = \" http://service.itcast.cn // \ "xmlns: xsd = \" http://www.w3.org/2001/XMLSchema \""

+ "Xmlns: xsi = \" http://www.w3.org/2001/XMLSchema-instance\ ">"

+ "<Soapenv: Body> <q0: sayHello> <arg0> lisi </arg0> <arg1> 10 </arg1> </q0: sayHello> </soapenv: body> </soapenv: Envelope> ";

6. Send the Request body through a stream:

// Obtain the output stream

OutputStream out = con. getOutputStream ();

Out. write (requestBody. getBytes ());

Out. close ();

7. The server returns normally:

Int code = con. getResponseCode ();

If (code = 200) {// The server returns normal

InputStream is = con. getInputStream ();

Byte [] B = new byte [1024];

StringBuffer sb = new StringBuffer ();

Int len = 0;

While (len = is. read (B ))! =-1 ){

String str = new String (B, 0, len, "UTF-8 ");

Sb. append (str );

}

System. out. println (sb. toString ());

Is. close ();

}

Con. disconnect ();

}

Related Article

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.