Use URLConnection to invoke axis1.4 developed webservice

Source: Internet
Author: User
Tags response code soapui

Write in front:

There are many ways to call WebService: 1. Generate the client code directly from the client using the tool, copy the code into the project and invoke it, 2. Use the corresponding WebService framework to invoke, for example, if our server development uses axis, then I can import the corresponding axis jar on the client side. Package, and then use its related methods to make the call; 3.js call; 4.URLConnection call. Above the first two ways personally think the comparison is applicable to the server and the client are Java development system, if it is a different language call that is not good to say. And the third and the fourth kind of way in fact, if in the JSP page to call the interface, the use of JS this way, if you need to write programs in the background to call, it is recommended URLConnection (now just will use, in fact, it's some of the principles of something I still very vague, For example, this method should be HTTP?? Call?? , it's not clear yet.)

The latest project is to develop the WebService interface, but the JDK is 1.4. The axis1.4 is chosen for development (this is the only environment that is more suitable for the project).

  

Here I also use the Java language to do the test, is can be called. The associated jar package is required to parse the data returned by the server:

Code:

 Packageedu.hue.client;ImportJava.io.BufferedReader;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.StringReader;Importjava.net.HttpURLConnection;Importjava.net.ProtocolException;ImportJava.net.URL;Importjava.net.URLConnection;Importjava.util.List;Importorg.dom4j.Document;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader; Public classXMLClient2 { Public Static voidMain (string[] args) {Try {                //Create a URL addressURL url =NewURL ("http://10.203.138.82:8080/test_axis3/services/sayHello?wsdl"); //Open ConnectionURLConnection conn =url.openconnection (); //convert into HttpurlHttpURLConnection Httpconn =(httpurlconnection) conn; System.setproperty ("Sun.net.client.defaultConnectTimeout", "30000"); System.setproperty ("Sun.net.client.defaultReadTimeout", "30000"); //turn on the input and output switchHttpconn.setdoinput (true); Httpconn.setdooutput (true); //Post submission cannot have cacheHttpconn.setusecaches (false); //Set Request ModeHttpconn.setrequestmethod ("POST"); //set the header information for the requestHttpconn.setrequestproperty ("Content-type", "Text/xml;charset=utf-8"); //set SOAPAction header or the error does not have this SOAPAction headerHttpconn.setrequestproperty ("SOAPAction", "" "); //Stitching Request message Here the request message body directly with the interface test tool SOAPUI to get then stitching the following note double quotes here to escape into the "String data = "<soapenv:envelope xmlns:soapenv=" + "\" http://schemas.xmlsoap.org/soap/envelope/\ "+" xmlns:ser=\ "http://server.hue.edu/\" "+" xmlns:xsd=\ "http://www.w3.o Rg/2001/xmlschema\ "" + "xmlns:xsi=\" http://www.w3.org/2001/xmlschema-instance\ ">"//+ "<soapenv:header/>"+ "<soapenv:Body>" + "<ser:say soapenv:encodingstyle=\" http://schemas.xmlsoap.org/soap/e Ncoding/\ ">" + "<name xsi:type=\" soapenc:string\ "xs:type=\" type:string\ "xmlns:soapenc=\" http                             ://schemas.xmlsoap.org/soap/encoding/\ "xmlns:xs=\" http://www.w3.org/2000/xmlschema-instance\ ">" + "Small mosquito qq:513996980"//this is copied directly in the SOAPUI, so its request message body is relatively long can also be used in the following way to stitch the comments+ "</name>" + "</ser:say>" + "</soapenv:Body>" + "</soapenv:Envelope>"; /*The following kind of request message body is more simple test can be successful its method name parameter name is very concise * but in order to insure that you want to write the request message body with the interface test tool to obtain such as SOAPUI and then directly copied over String data = "<soapenv:envelope xmlns:soapenv=" + "\"http://schemas.xmlsoap.org/soap/envelope/\ "" + "xmlns:ser=\"http://server.hue.edu/\ "" + "xmlns:xsd=\"Http://www.w3.org/2001/XMLSchema\ "" + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\ ">" + "<soapenv:header/>" + "<soapenv:Body>"                        + "<ser:say >" + "<name> small mosquito qq:513996980</name>" + "</ser:say>" + "</soapenv:Body>" + "</soapenv:Envelope>"; /c5>*/                                                              //get the output streamOutputStream out =Httpconn.getoutputstream (); //Send the data here note to take the code utf-8 or not pass the Chinese parameter pastOut.write (Data.getbytes ("UTF-8")); //determine the success of the request                if(Httpconn.getresponsecode () = = 200) {System.out.println ("Call succeeded ..."); //Get input streamInputStream in =Httpconn.getinputstream (); //buffers using the input streamBufferedReader reader =NewBufferedReader (NewInputStreamReader (In, "UTF-8")); StringBuffer SB=NewStringBuffer (); String Line=NULL; //Read input stream                     while(line = Reader.readline ())! =NULL) {sb.append (line); }                                        //to create a sax reader, you need to import the appropriate jar package hereSaxreader Saxreader =NewSaxreader (); //Create a Document objectDocument doc = Saxreader.read (NewStringReader (sb.tostring ())); //GET Request Response return element here is the name of the node where you can view the return value of your corresponding message body according to the interface test Tool I'm Sayreturn here .List eles = doc.selectnodes ("//sayreturn");  for(intI=0;i<eles.size (); i++) {Element ele=(Element) eles.get (i);                    System.out.println (Ele.gettext ());            } System.out.println (Sb.tostring ()); }Else{//call failed to print error information//Get input streamInputStream err =Httpconn.geterrorstream (); //buffers using the input streamBufferedReader reader =NewBufferedReader (NewInputStreamReader (Err, "UTF-8")); StringBuffer SB=NewStringBuffer (); String Line=NULL; //Read input stream                 while(line = Reader.readline ())! =NULL) {sb.append (line); } System.out.println ("Return error code:" +Httpconn.getresponsecode ()); System.out.println ("Returned result:" +sb.tostring ()); }                } Catch(Exception e) {e.printstacktrace (); }}}

The above is the code of the client call, the server here is not a lot of paste, just a method, there is a string type parameter.

  Summary of issues:

  1. Reported an error saying HTTP response result Code 500:

Java.io.IOException:Server returned HTTP response code:500 for url:http://10.203.138.82:8080/test_axis/services/ SayHello
At Sun.net.www.protocol.http.HttpURLConnection.getInputStream (httpurlconnection.java:1626)

Here's the 500 error is generally your code has a problem where may write a bit wrong this time to carefully and carefully then try to use a different way to eliminate the wrong place also need to more Baidu, here I appear this problem is because the input stream is written in front of the output stream (for the client, The output stream should be written before the input stream get is written. InputStream ())

2. Bug:axisfault FaultCode for axis1.4: {http://xml.apache.org/axis/}client.nosoapaction faultsubcode:faultstring : No SOAPAction header! FaultActor:faultNode:faultDetail: {http://xml.apache.org/axis/}stacktrace:no soapaction header!

No SOAPAction header! It's important to note that if you make this mistake with a single line of code, it would be nice to have read a blog post for this mistake for almost a day or two, but no one has ever told a specific code workaround (there are two workarounds 1: Add SOAPAction to the client, its content is unimportant, and writing an empty string can be 2: Service-side Rewrite write a servlet, like Axisservlet, and rewrite the inside of the Getsoapaction () method, this recommendation is only the first, after all, this is not the axis of the bug)

Set SOAPAction header or the error does not have this soapaction header
Httpconn.setrequestproperty ("SOAPAction", "" ");

3. If the client passes the parameter in Chinese, the error is: when it becomes a byte array, add UTF-8

Get the output stream
OutputStream out = Httpconn.getoutputstream ();
Send the data here note to take the code utf-8 or not pass the Chinese parameter past
Out.write (Data.getbytes ("UTF-8"));

  Questions:

How do I call a method if it has no arguments??? The interface method called when the WCF-developed. NET system was invoked before the cross-platform is not required to pass parameters but also passed an empty string. There's no SOAP request message body or anything, but here, because it's webservice, it's soap-based, so here's the data. Regardless of whether the parameters should be written on the message request body, so here need to pay attention to

Like what:

// But for insurance, I want you to write the request message body with the interface test tool to get, say, soapui    and copy it directly.                      String data = "<soapenv:envelope xmlns:soapenv=" +                        "\" http://schemas.xmlsoap.org/soap/envelope/\ "" +                        " Xmlns:ser=\ "http://server.hue.edu/\" "+                        " xmlns:xsd=\ "http://www.w3.org/2001/xmlschema\" "+                        " xmlns:xsi=\ " Http://www.w3.org/2001/xmlschema-instance\ ">"                        + "<soapenv:header/>"                        + "<soapenv:Body>"                        + "<ser:say >"                        // For example, the method you want to call here doesn't have to be written without parameters, but the message body should    still be.                        + "</ser:say>"                        + "</soapenv:Body>"                      + "</soapenv:Envelope>";

Use URLConnection to invoke axis1.4 developed WebService

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.