Axis2 calls WebService several ways

Source: Internet
Author: User
Tags addchild wsdl

There are three main ways of doing this:

First RPC mode, no client code generated

Second,document mode, do not generate client code

Third, use the wsdl2java tool to generate a client-side call

Java code:

     Packagesamples.quickstart.client; ImportJavax.xml.namespace.QName; Importorg.apache.axiom.om.OMAbstractFactory; Importorg.apache.axiom.om.OMElement; Importorg.apache.axiom.om.OMFactory; ImportOrg.apache.axiom.om.OMNamespace; ImportOrg.apache.axis2.AxisFault; Importorg.apache.axis2.addressing.EndpointReference; Importorg.apache.axis2.client.Options; Importorg.apache.axis2.client.ServiceClient; Importorg.apache.axis2.rpc.client.RPCServiceClient; Importsamples.quickstart.StockQuoteServiceStub; ImportSamples.quickstart.xsd.GetPrice; ImportSamples.quickstart.xsd.GetPriceResponse;  Public classstockquoteclient {/*** Method One: * Apply RPC method call this way is equal to the remote call, * that is, through the URL location to tell the remote server, the method name, parameters, etc., call the remote service, get the results. * Use the Org.apache.axis2.rpc.client.RPCServiceClient class to invoke WebService * "Note": If the called WebService method has a return The return value should use the Invokeblocking method the method has three parameters the type of the first parameter is the QName object that represents the method name to invoke, the second parameter represents the parameter value of the WebService method to invoke, the parameter type is O              Bject[]; When a method has no arguments, the second parameter value of the Invokeblocking method cannot be null, but new object[]{} is used.                                    The third parameter represents the class object of the return value type of the WebService method, and the parameter type is class[].            If the called WebService method does not return a value, the method should use the Invokerobust method with only two parameters, which have the same meaning as the first two parameters of the Invokeblocking method.       When you create a QName object, the first parameter of the constructor method of the QName class represents the namespace name of the WSDL file, which is the targetnamespace attribute value of the <wsdl:definitions> element. *       */       Public Static voidtestrpcclient () {Try {          //axis1 Service Side//String url = "http://localhost: 8080/stockquote/services/stockquoteservicesoap11port?wsdl "; //Axis2 Service SideString url = "HTTP://LOCALHOST:8080/AXIS2SERVERDEMO/SERVICES/STOCKQUOTESERVICE?WSDL"; //call WebService using RPC modeRpcserviceclient serviceclient =Newrpcserviceclient (); //Specifies the URL to call WebServiceEndpointReference Targetepr =Newendpointreference (URL); Options Options=serviceclient.getoptions (); //Determine destination service addressOptions.setto (TARGETEPR); //determining the Calling methodOptions.setaction ("Urn:getprice"); /*** Specify the GetPrice method to invoke and the namespace of the WSDL file * If the WebService service driven by Axis2 writing * The problem caused by the namespace inconsistency * org.apache.axis2.AxisFault:java.lang.RuntimeException:Unexpected subelement arg0*/QName QName=NewQName ("Http://quickstart.samples/xsd", "GetPrice"); //specifying the parameter value of the GetPrice methodobject[] Parameters =NewObject[] {"13" }; //class object specifying the data type of the GetPrice method return valueclass[] Returntypes =NewClass[] {Double.class }; //call method One pass parameter, invoke service, get service return result setomelement element =serviceclient.invokeblocking (QName, parameters); //It is worth noting that the returned result is an XML string encapsulated by the Omelement object. //we can apply it flexibly, and below I take the first element value and print it. Because the called method returns a resultString result =element.getfirstelement (). GetText ();          SYSTEM.OUT.PRINTLN (result); //Call method Two GetPrice method and output The return value of the methodobject[] Response =serviceclient.invokeblocking (QName, parameters, returntypes); //String r = (string) response[0];Double r = (double) response[0];        System.out.println (R); } Catch(Axisfault e) {e.printstacktrace (); }      }      /*** Method Two: Application of document mode call * Using Ducument method is cumbersome and flexible. It's more used now. Because we really get rid of the coupling we don't want.*/       Public Static voidtestdocument () {Try {          //String url = "http://localhost: 8080/axis2serverdemo/services/stockquoteservice ";String url = "HTTP://LOCALHOST:8080/STOCKQUOTE/SERVICES/STOCKQUOTESERVICESOAP11PORT?WSDL"; Options Options=NewOptions (); //Specifies the URL to call WebServiceEndpointReference Targetepr =Newendpointreference (URL);          Options.setto (TARGETEPR); //options.setaction ("Urn:getprice");serviceclient Sender=Newserviceclient ();                              Sender.setoptions (options); Omfactory FAC=omabstractfactory.getomfactory (); String TNS= "Http://quickstart.samples/"; //Namespaces , and sometimes namespaces don't add up okay, but better to add, because sometimes things happen, you know.Omnamespace omns = Fac.createomnamespace (TNS, ""); Omelement Method= Fac.createomelement ("GetPrice", Omns); Omelement symbol= Fac.createomelement ("symbol", Omns); //Symbol.settext ("1");Symbol.addchild (Fac.createomtext (symbol, "Axis2 Echo String"));          Method.addchild (symbol);                    Method.build (); Omelement result=sender.sendreceive (method);        SYSTEM.OUT.PRINTLN (result); } Catch(Axisfault axisfault) {axisfault.printstacktrace (); }      }     /*** Construct validation information for the SOAP header, * If your server is not verified, then you do not need to add the verification information in the header * *@paramServiceClient *@paramTNS Namespace *@paramUser *@paramPasswrod*/       Public voidaddvalidation (serviceclient serviceclient, string TNS, String user, String passwrod) {omfactory FAC=omabstractfactory.getomfactory (); Omnamespace Omns= Fac.createomnamespace (TNS, "NSL"); Omelement Header= Fac.createomelement ("Authenticationtoken", Omns); Omelement Ome_user= Fac.createomelement ("Username", Omns); Omelement Ome_pass= Fac.createomelement ("Password", Omns);        Ome_user.settext (user);                Ome_pass.settext (Passwrod);        Header.addchild (Ome_user);        Header.addchild (Ome_pass);      Serviceclient.addheader (header); }            /*** Method Three: Generate client mode calls with Axis2 plugin **/       Public Static voidtestcodeclient () {Try{String URL= "Http://localhost:8080/axis2ServerDemo/services/StockQuoteService"; Stockquoteservicestub stub=Newstockquoteservicestub (URL); GetPrice Request=NewGetPrice (); Request.setsymbol ("ABCD"); Getpriceresponse Response=Stub.getprice (Request);        System.out.println (Response.get_return ()); } Catch(Org.apache.axis2.AxisFault e) {e.printstacktrace (); } Catch(java.rmi.RemoteException e) {e.printstacktrace (); }      }       Public Static voidMain (string[] args) {stockquoteclient.testrpcclient (); //stockquoteclient.testdocument (); //stockquoteclient.testcodeclient ();      }    }

WSDL2Java is used to generate the appropriate server-side and client code generation tools based on WSDL.
The command line format is: WSDL2Java [options]-uri <url or path>: a URL or path to A WSDL

For example:

Wsdl2java-uri http://localhost:8080/cxfService_0617/services/Hellows?wsdl-s-O build\client

The options that are commonly used are as follows:
-O <path>: Specifies the output path of the generated code
-A: Generate code for asynchronous patterns
-S: Generate code for synchronous mode
-P <pkg>: Specify the package name for the code
-L <languange>: Used language (java/c) default is Java
-T: Generating test Cases for code
-SS: Generate server-side code is not generated by default
-SD: Generate service description file Services.xml, used only with-SS
-D <databinding>: Specify Databingding, for example, Adb,xmlbean,jibx,jaxme and Jaxbri
-G: Generate the server and client code
-PN <port_name>: When there are multiple ports in the WSDL, specify one of the ports
-SN <serv_name>: Select a service in the WSDL
-U: Expand the class of data-binding
-R <path>: Specify a repository for code generation
-ssi: Implementing code Generation Interface classes for the service side
-S: Specify the storage path for the generated source code
-r: Specify a storage path for the generated resources
–nobuildxml: Build.xml file not generated in output
–NOWSDL: The WSDL file is not generated in the resources directory
–nomessagereceiver: Do not generate Messagereceiver class

Axis2 calls WebService several ways

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.