"WebService" takes you into the WebService world.

Source: Internet
Author: User
Tags http request soap socket versions xmlns port number wsdl

WebService Series Articles:
"WebService" Custom WebService service and its invocation
"WebService" WSDL configuration in detail and using annotations to modify the WSDL configuration
"WebService" CXF processing complex types such as JavaBean and map data
Settings for "WebService" CXF interceptors and custom CXF interceptors 1. What's WebService ?

To be exact, WebService is not a technology, but a specification. is a cross-platform, cross-language specification for interactions between applications that are developed across different platforms and languages.
For example, there is a C # on a Windows Server server. NET development of application A, on Linux has a Java language development of application B, now B application to call a application, or call each other, to view the other's business data, you need to webservice specifications.
Another example is the weather forecast interface. Countless applications need to obtain weather information, these applications may be a variety of platforms, a variety of technical implementation, and the Meteorological Bureau of the project, estimated one or two, to provide weather information to the outside, this time, how to solve it. WebService is a specification defined for the above-mentioned requirements.
We typically develop webservice interfaces on specific platforms and invoke WebService interfaces, each of which has its own WebService implementation framework. Java, for example, has Apache Axis1, Apache Axis2, Codehaus XFire, Apache CXF, Apache Wink, Jboss Resteasyd, and so on. The Apache CXF used more, it can also be integrated with spring. 2. Revisit the socket

Before analyzing how to call WebService, let's recall how the traditional socket communicates, which makes it easier to understand WS. 2.1 Creating a Web service based on a socket

Why use a socket? Take a look at the schematic diagram below:

As can be seen from the diagram, between program A and program B is not possible to achieve a direct call, then a need to access B, a is to create a socket and a B machine port number, before B has been created in the local socket waiting for the user to connect, a and B after the successful connection, can send a request to B to obtain data, which is very good understanding, in order to recall the creation and use of the socket, the following first write a simple socket communication demo, the server can be lowercase letters to uppercase. 2.2 Classic Socket service

Client:

/** * @Description socket Client for sending to server request * @author Ni SHENGWU * */public class Socketclient {public static void

        Main (string[] args) throws Exception {Scanner input = new Scanner (system.in);
        1: Create a TCP protocol-based socket service to specify the connection server and port number when establishing the object socket SC = new socket ("127.0.0.1", 9999);

        2: Get the output stream in the socket through the established socket object, call the Getoutstream method OutputStream out = Sc.getoutputstream ();
        System.out.println ("Please enter the letter to be converted:");
        String InitData = Input.next ();//Get the console input///3: Write to the socket output stream Out.write (Initdata.getbytes ());

        System.out.println ("Wait for server-side return data");
        4: Through the established socket object to get the input stream in the socket, the input stream will accept data from server side InputStream in = Sc.getinputstream ();

        Byte[] B = new byte[1024];
        5: Get the input byte stream data, note that this method is blocked, if not get data will always wait for int len = In.read (b);

        SYSTEM.OUT.PRINTLN ("The result returned is:" + new String (b, 0, Len));
        Close socket Out.close ();
        In.close ();
        Sc.close (); InchPut.close (); }
}

Server side:

/** * @Description socket server, to receive client requests, to implement the Capitalize function * @author Ni SHENGWU * */public class Socketserver {public Stati c void Main (string[] args) throws Exception {//1: Establishing a server-side TCP socket service, must listen on a port serversocket ss = New Ser
        Versocket (9999);

            while (true) {System.out.println ("Wait for client request ...");
            2: Get the Client object on the connection through the accept method of the socket object on the server side, no plug, wait for socket socket = ss.accept ();

            SYSTEM.OUT.PRINTLN ("Handshake succeeded ...");
            3: Get data via input stream InputStream input = Socket.getinputstream ();
            Byte[] B = new byte[1024];
            int len = Input.read (b);
            String data = new String (b, 0, Len);

            SYSTEM.OUT.PRINTLN ("Client data is:" + data);
            4: Through the server-side socket output stream, write data, will be transmitted to the client socket input stream OutputStream out = Socket.getoutputstream ();

            Out.write (Data.touppercase (). GetBytes ());
            5: Close socket out.close ();
            Input.close (); SockEt.close (); }
    }
}

This demo is very simple, first open the server side of the program, wait, and then open the client program, if the console input hello past, will return a hello back from the server, indicating that the socket communication is successful. 2.3 Web Program Access socket Service

The above classic demo is two Java programs written locally, we now have a lot of projects are Web projects, that is, through the browser to interact, we look at the way through the browser to access the Socketservice service. Server or use the above Java program, the client I changed into a browser request, the new write a JSP as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Pay attention to the request address of the action, including the port to be the same as the server, so that when we commit to access the above service-side program. Look at the server running results:

can see that the Web program does and the service side handshake succeeds, and the data can be passed, Sname=hello, including some HTTP information can be passed, but we will look at the server back to the browser data is what:

I use a Chrome browser, and other browsers may not have data, which is possible, but from the data, it simply turns all the information into uppercase ... And it doesn't have an HTTP return format, which means that all I need is an uppercase Hello, so this is problematic.
So it can be summed up: different protocols are actually support socket communication. The Web program can call the socket request, but because of the protocol is different, so in the processing time to filter the HTTP protocol format, return the time also need to add HTTP return format, otherwise there will be problems, imagine, if also to deal with the protocol format, is very troublesome.
So here, basically understand why the traditional socket can not meet the demand, in fact, in addition to the above drawbacks, there are other drawbacks, such as if the parameters of a lot, it is not good maintenance, and so on, here are not many examples. 3. Call the published WebService

About WebService itself, I do not do too much description, at the top also has a simple introduction, since the traditional socket communication can not be satisfied, then the following start to call the published WS, really into the world of WS.
There is a site: http://www.webxml.com.cn, a company in Shanghai to do, the above provides a lot of WS services, which has a query number attribution to the function, we use it to do the test. First, test them in their site, and then write the program locally to invoke the WS service to get the query results.
Look at the query on the site:

After entering the mobile number attribution to query the Web service,

Choose Getmobilecodeinfo, you can go to the query page,

After the call will appear <string xmlns= "http://WebXml.com.cn/" >18312345678: Guangdong Shenzhen, Guangdong Mobile Global card </string> results. This is the result of calling WS, and next we call this WS in the program. 3.1 GET request mode

In a Java program, if you want to send an HTTP request, you need to use the HttpClient tool. HttpClient is a sub-project under Apache Jakarta Common that can be used to provide efficient, up-to-date, feature-rich client programming toolkits that support the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol.
Why use the HttpClient tool? Because the original socket is based on the transport layer, now we want to access the WebService is based on the application layer of HTTP, so our socket communication to the use of HttpClient HTTP request, so that the format to match.

/**
 * @Description Get method Request
 * @param number
 * @throws Exception
 *
/public void Get (String number) Throws Exception {
    //httpclient: Simulate HTTP request in Java code
    //Create Browser object
    HttpClient client = new HttpClient ();
    Fill in the data, send a GET or POST request
    GetMethod get = new GetMethod ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"
            + "/getmobilecodeinfo?mobilecode=" + number + "&userid=");
    Specifies the format of the transfer as GET request format
    get.setrequestheader ("Content-type", "text/xml; Charset=utf-8 ");
    Send request
    int code = Client.executemethod (get);
    System.out.println ("Http: Status Code:" + code);

    String result = Get.getresponsebodyasstring ();
    SYSTEM.OUT.PRINTLN ("The result returned is:" + result);
}

As can be seen from the program, the requested host is ws.webxml.com.cn, these URLs are available on the WS provider's website, we only need to write a pair to request WS, and in the main method call this method to get the results in the console. 3.2 POST Request mode

The request process is the same, but the URL and transmission format is different, modify the corresponding place,

/**
 * @Description Post method Request
 * @param number
 * @throws Exception
 *
/public void post (String number) Throws Exception {
    //httpclient: Simulate HTTP request in Java code
    //Create Browser object
    HttpClient client = new HttpClient ();
    Fill in the data, send a GET or POST request
    Postmethod post = new Postmethod ("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/ Getmobilecodeinfo ");

    Specifies the format of the transfer as the default post format
    post.setrequestheader ("Content-type", "application/x-www-form-urlencoded");     
    Transmission parameter
    post.setparameter ("Mobilecode", number);
    Post.setparameter ("UserID", "");

    Send request
    int code = Client.executemethod (post);
    System.out.println ("Http: Status Code:" + code);

    String result = Post.getresponsebodyasstring ();
    SYSTEM.OUT.PRINTLN ("The result returned is:" + result);
}
3.3 Soap Method Request

This is also used in many ways, it has two versions soap1.1 and soap1.2,jdk1.7 and above can be used soap1.2.

/**
 * @Description The SOAP post method request, but the transmitted data is in XML format, facilitates the maintenance of the data
 * @param number
 * @throws Exception
*/ public void Soap (String number) throws Exception {
    //httpclient: simulates an HTTP request in Java code
    //creates a browser object
    HttpClient Client = new HttpClient ();
    Fill in data, send get or POST request
    Postmethod post = new Postmethod ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx") ;

    Specifies the format of the transfer in XML format
    post.setrequestheader ("Content-type", "Application/soap+xml;charset=utf-8");
    Transfer XML, load Soap.txt
    post.setrequestbody (New FileInputStream ("E:/github/client/src/soap.txt"));  
    Send request
    int code = Client.executemethod (post);
    System.out.println ("Http: Status Code:" + code);

    String result = Post.getresponsebodyasstring ();
    If you are using SOAP, the returned data is also the XML-based SOAP format
    System.out.println ("The result returned is:" + result);
}

Because the SOAP method needs to send XML to the server, we can implement a TXT document that contains XML data, which the WS provider will provide, and we need to write it well:

<?xml version= "1.0" encoding= "Utf-8"?> <soap12:envelope
xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:xsd=" Http://www.w3.org/2001/XMLSchema "xmlns:soap12=" http://www.w3.org/2003/05/ Soap-envelope ">
  <soap12:Body>
    <getmobilecodeinfo xmlns=" http://WebXml.com.cn/">
      < mobilecode>18312345678</mobilecode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>

The above methods recommend the use of SOAP, but essentially HTTP invocation, but only when the call can transfer XML data. And HttpClient is Java's solution to invoke the HTTP protocol, but there is no guarantee that other languages will have similar tools. So the WS-recommended scenario is to use the Wsimport command. This is also the focus of the analysis below. 3.4 Using Wsimport

Each WS will have a wsdl,wsdl-WebService Description language–web Service Description Language. It is an XML representation of where the service is-the address. Describe what method the service provides in XML form – how to invoke it. We can use this WSDL to get information about this WS, including the class and Java code. I'll take a look at what I'm going to do with this WSDL later in this section.
Wsimport is a command, jdk1.6 and above can be used, WS for different languages will have a wsimport command, we can find this wsimport.exe in the bin directory of our own installed JDK, because of this, so we can use the command line Wsimport command. How to use it.
Each WS will have a WSDL, take the above the attribution Query service, above the second picture above a service description, click on to see the WSDL, of course, you can also directly access the browser URL to access the WSDL, the XML document. As follows:

Now just copy the URL, then open a command Prompt window, go to a directory (the directory to save the generated and WS-related files, you can build one in advance), run
Wsimport Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL
will generate the corresponding JavaBean, of course, is the. class file, but we do not want the class file, we want the Java file, so you can use the following command:
Wsimport-s Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL
This not only generated a class file, but also generated a Java file, if we want to build these files under a fixed package, and so it is convenient to copy directly into the project, you can use the following command:
Wsimport-s. -P ws.client.c Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL
This will generate the required class and Java code in the directory ws/client/c/, and then we delete the class file, copy the WS directory directly into the project, as follows (_main I wrote, used to invoke):

This gives the number attribution to query the WS service related API, which is generated by the official WSDL, and then how do we use it in our own projects. I write a new _main.java file, directly using these APIs, as follows:

public class _main {public
    static void Main (string[] args) {

        //Get a WS service
        mobilecodews ws = New Mobilecodews () ;
        Get the specific service type: Get post soap1.1 soap1.2
        mobilecodewssoap wssoap = Ws.getmobilecodewssoap ();
        String address = Wssoap.getmobilecodeinfo ("18312345678", null);
        SYSTEM.OUT.PRINTLN ("Cell phone attribution information is:" + address);
    }
}

This is very convenient, now completely without the above kind of connection Ah, set the address AH and so on, directly encapsulated, I call these APIs directly can invoke remote webservice. This is also the official recommendation of a method, of course, we can also package the generated class file into a jar to put into the project. After running this main method, we also return directly to the attribution, without those tags, which is what is needed in development.
Here basically already call WebService, and finally briefly summed up, WS in this WSDL is very important, here in XML describes the WS information, so we can parse the WSDL to obtain the WS-Related API, You can then invoke the WS in your own project by invoking these APIs.
  

-willing to share and progress together.
-My Blog home: http://blog.csdn.net/eson_15

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.