Java client calling Web Service Based on JAX-WS

Source: Internet
Author: User

Java client calling Web Service Based on JAX-WS generally adopts two methods: proxy method and dispatch method.
The proxy method is as follows:

1. The proxy method call code snippets are generally as follows:

URL wsdlURL = new URL("file:///D:/JAVAWorkspace/Test/WSClient/src/wsdl/prjCXFWeb.wsdl");QName serviceQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderService");QName portQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderPort");Service service = Service.create(wsdlURL, serviceQName);WSCXFProvider port = (WSCXFProvider) service.getPort(portQName, WSCXFProvider.class);try{    System.out.println(port.testWS("message"));}catch(SOAPFaultException e){    System.out.println(e.getFault().getFaultCode());    System.out.println(e.getFault().getFaultString());}

1. Use a tool to generate a service endpoint interface (SEI) and a Java interface through the WSDL file, which can provide functions for the web service. The class name of this interface maps to the porttype name of the WSDL, the method corresponds to operation, and the method parameters correspond to message and types. Both cxf and axis provide the following tool: wsdl2java. [The above wscxfprovider Is Sei]
2. initialize the service and specify the wsdl url and service QNAME. The first part of the service QNAME is the namespace, And the last part is the name: service name = "wscxfproviderservice">. Then, get an instance that implements sei through getport, which is called proxy. Its QNAME corresponds to the <WSDL: Port name = "wscxfproviderport" section in the WSDL file.
3. Call web service through sei. The parameter passed to SEI is the Java class added with jaxb annotation (simple type and string do not need to be marked ).
4. The input parameters are serialized into the payload (XML in the body part) of the SOAP message. This is because of the service. getport is created through the proxy mechanism. When the proxy method is called, The invocationhandler method associated with it will also be executed. The invoke method will serialize Java parameters to XML through jaxb. Then, the SOAP request is sent to the server.
5. Return response is similar to 4. invocationhandler is responsible for deserializing XML into Java objects using jaxb.

Ii. Dispatch method: the payload and message methods are available for dispatch.
In payload mode, the client needs to focus on the body part of the SOAP message. You can pass the Java object or XML source with jaxb annotation to dispatch to call the web service.
1. Use jaxb Java object in payload mode:
Sample Code:

// create ServiceURL wsdlURL = new URL("file:///D:/JAVAWorkspace/Test/WSClient/src/wsdl/prjCXFWeb.wsdl");QName serviceQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderService");Service service = Service.create(wsdlURL, serviceQName);JAXBContext ctxt = JAXBContext.newInstance(MyRequest.class, MyResponse.class);QName portQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderPort");Dispatch<Object> dispatchJAXB = service.createDispatch(portQName, ctxt, Service.Mode.PAYLOAD);// create the custom request order objectMyRequest myReq = new MyRequest();myReq.arg0="message";MyResponse resp = (MyResponse) dispatchJAXB.invoke(myReq);System.out.println(resp.get_return());

Myrequest is a class labeled with jaxb:

@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "testWS", propOrder = {    "arg0"})@XmlRootElement(name = "testWS")public class MyRequest {     protected String arg0;    public String getArg0() {        return arg0;    }    public void setArg0(String arg0) {        this.arg0 = arg0;    }}

Myresponse is also added with jaxb annotation class:

@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "testWSResponse", propOrder = {    "_return"})@XmlRootElement(name = "testWSResponse", namespace="http://test.cxf.bt.com/")public class MyResponse {    @XmlElement(name = "return")    protected String _return;    public String get_return() {        return _return;    }    public void set_return(String _return) {        this._return = _return;    }   }

Some tools generate jaxb clients (myrequest and myresponse) without @ xmlrootelement. * unable to handle al type "..... "As an element because it is missing an @ xmlrootelement annotation]. You need to manually add the xmlrootelement annotation.

2.1, payload uses XML Source:Only the XML payload content is imported, and the envelope part of the SOAP message is not required.

StreamSource xmlSource = new StreamSource(new StringReader(        "<dlwmin:testWS xmlns:dlwmin=/"http://test.cxf.bt.com//"><arg0>xxx</arg0></dlwmin:testWS>"));// create ServiceURL wsdlURL = new URL("file:///D:/JAVAWorkspace/Test/WSClient/src/wsdl/prjCXFWeb.wsdl");QName serviceQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderService");Service service = Service.create(wsdlURL, serviceQName);// create Dispatch<Source>QName portQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderPort");Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);Source orderSource = dispatch.invoke(xmlSource);// Process the response.StreamResult result = new StreamResult(new ByteArrayOutputStream());Transformer trans = TransformerFactory.newInstance().newTransformer();trans.transform(orderSource, result);ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();// Write out the response content.String responseContent = new String(baos.toByteArray());System.out.println(responseContent);

2.2. the message method uses XML Source:The XML content of the entire SOAP message.

StreamSource xmlSource1 = new StreamSource(    new StringReader(            "<?xml version=/"1.0/" encoding=/"utf-8/" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV=/"http://schemas.xmlsoap.org/soap/envelope//" xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/"><SOAP-ENV:Header/><SOAP-ENV:Body><dlwmin:testWS xmlns:dlwmin=/"http://test.cxf.bt.com//"><arg0>xxx</arg0></dlwmin:testWS></SOAP-ENV:Body></SOAP-ENV:Envelope>"));// create ServiceURL wsdlURL = new URL("file:///D:/JAVAWorkspace/Test/WSClient/src/wsdl/prjCXFWeb.wsdl");QName serviceQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderService");Service service = Service.create(wsdlURL, serviceQName);// create Dispatch<Source>QName portQName = new QName("http://test.cxf.bt.com/", "WSCXFProviderPort");Dispatch<SOAPMessage> dispatch = service.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);MessageFactory factory = MessageFactory.newInstance();SOAPMessage message = factory.createMessage();message.getSOAPPart().setContent(xmlSource1);message.saveChanges();SOAPMessage response = dispatch.invoke(message);SOAPPart sp = response.getSOAPPart();Source resp = sp.getContent();// Process the response.StreamResult result = new StreamResult(new ByteArrayOutputStream());Transformer trans = TransformerFactory.newInstance().newTransformer();trans.transform(resp, result);ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();// Write out the response content.String responseContent = new String(baos.toByteArray());System.out.println(responseContent);

2.3, The JAX-WS still supports calling using RPCBut it is not encouraged at all (the server-side service provider class must be extends remote). The following is a call example of customer service: the class under javax. xml. RPC is introduced.

package com.test.jaxws.caller;import java.net.MalformedURLException;import java.net.URL;import java.rmi.RemoteException;import javax.xml.namespace.QName;import javax.xml.rpc.Service;import javax.xml.rpc.ServiceException;import javax.xml.rpc.ServiceFactory;import com.cxfws.test.SimpleService;public class JAXRPCWSCaller {    static String wsdlLocation = "file:///D:/JAVAWorkspace/Repository/prjCXFWS/src/wsdl/prjCXFWS.wsdl";    // SimpleService must extends Remote if using this way to call web service    public static void main(String[] args) throws MalformedURLException, ServiceException, RemoteException {        ServiceFactory serviceFactory = ServiceFactory.newInstance();        Service service = serviceFactory.createService(new URL(wsdlLocation), new QName("http://test.cxfws.com/",                "SimpleServiceService"));        SimpleService myProxy = (SimpleService) service.getPort(                new QName("http://test.cxfws.com/", "SimpleServicePort"), SimpleService.class);        String result = myProxy.concatenate("s1", "s2");        System.out.println(result);    }}

2.4. If the server side is not implemented in Java, you can only use rpc. Call of soap. jar.[The example below is a very old code...]

package com.test.soaprpc.caller;import java.net.URL;import java.util.Arrays;import java.util.Vector;import org.apache.soap.Constants;import org.apache.soap.Fault;import org.apache.soap.Header;import org.apache.soap.encoding.SOAPMappingRegistry;import org.apache.soap.encoding.soapenc.StringDeserializer;import org.apache.soap.rpc.Call;import org.apache.soap.rpc.Parameter;import org.apache.soap.rpc.Response;import org.apache.soap.util.xml.QName;public class WSCallerBySOAP {    public Object callWS(Parameter[] params, String uri, String mtdName, String url, SOAPMappingRegistry smr) {               try {            Call call = new Call();               call.setTargetObjectURI(uri);            call.setMethodName(mtdName);            call.setParams(new Vector(Arrays.asList(params)));                       call.setSOAPMappingRegistry(smr);                       Header myHeader = new Header();            myHeader.declareNamespace("", " XXX ");            myHeader.setAttribute(new QName("", "Minor"), "0");            call.setHeader(myHeader);            Response resp = call.invoke(new URL(url), "");                       if (resp.generatedFault()) {                Fault fault = resp.getFault();                System.out.println(fault.getFaultCode());                System.out.println(fault.getFaultString());            } else {                if (resp.getReturnValue() != null) {                    Object obj = resp.getReturnValue().getValue();                    return obj;                }            }        } catch (Exception e) {            e.printStackTrace();            System.out.println(e);        }        return null;    }    public static void main(String[] args) {        WSCallerBySOAP wsCaller = new WSCallerBySOAP();        Parameter param1 = new Parameter("arg0", String.class, "<test:testWS>" + "<arg0>aaaaaaaaaa</arg0>"                + "</test:testWS>", Constants.NS_URI_SOAP_ENC);        Parameter[] prams = new Parameter[] { param1 };        String uri = "WSCXFProviderPort";        String url = "http://localhost:7225/prjCXFWeb/services/WSCXFProviderPort";        String mtdName = "testWS";        SOAPMappingRegistry smr = new SOAPMappingRegistry();        smr.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("", "return"), null, null, new StringDeserializer());        System.out.println(wsCaller.callWS(prams, uri, mtdName, url, smr));    }}

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.