Java calls WebService Methods (2) - JAX-WS call WebService

The need to introduce other frameworks with JAX-WS (Java API for XML Web Services) call WebService, all comes with the JDK.

1, ready

Reference Java call WebService Methods (1) - Preparations

2, call

2.1, Dispatch way

Dispatch Payload way there and Message in two ways.

2.1.1, Payload way

In the payload, the only body part of the incoming SOAP message.

/**
 * dispatch Payload方式调用WebService
 * @param portName 端口名称
 * @param param 参数
 */
public static void dispatchPayload(String portName, String param) {
    try {
        StringBuffer source = new StringBuffer();
        source.append("<web:toTraditionalChinese xmlns:web=\"" + targetNamespace + "\">");
        source.append("<web:sText>").append(param).append("</web:sText>");
        source.append("</web:toTraditionalChinese>");
        StreamSource xmlSource = new new StreamSource ( new new StringReader (source.toString ())); 
        
        the URL of wsdlURL = new new the URL of (url); 
        QName serviceQName = new new QName (targetNamespace, "TraditionalSimplifiedWebService" ); 
        Service Service = Service.create (wsdlURL, serviceQName); 
        QName portQName = new new QName (targetNamespace, portName); 
        dispatch <Source> dispatch = service.createDispatch (. portQName, Source class , Service.Mode.PAYLOAD); 
        
        // the .NET server-side Soap1.1 needed, without error will be reported: server failed to recognize the value of HTTP header SOAPAction
        Map<String, Object> requestContext = dispatch.getRequestContext();
        requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
        requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese");
        
        Source orderSource = dispatch.invoke(xmlSource);
        StreamResult result = new StreamResult(new ByteArrayOutputStream());
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.transform(orderSource, result);
        ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
        String responseContent = new String(baos.toByteArray());
        System.out.println(responseContent);

        Reader file = new StringReader(responseContent);
        SAXReader reader = new SAXReader();
        Document dc = reader.read(file);
        Element root = dc.getRootElement();
        String r = root.elementText("toTraditionalChineseResult").trim();
        System.out.println(r);

    } catch (Exception e) {
        e.printStackTrace (); 
    } 
}

2.1.2, Message mode

In Message mode, we have the whole Soap incoming messages.

/ ** 
 * Payload dispatch invoke WebService 
 * @param soapNamespace the SOAP message namespace entire message body, Soap1.1 and Soap1.2 not the same 
 * @param portName port name 
 * @param param parameter
  * / 
public  static  void DispatchMessage (String soapNamespace, the portName String, String param) {
     the try { 
        the StringBuffer Source = new new the StringBuffer (); 
        source.append ( "<soapenv: Envelope xmlns: soapenv = \" "+ soapNamespace +" \ "xmlns: Web = \" "+ the targetNamespace + "\"> " ); 
        source.append ( " <soapenv: Header /> " );
        source.append("<soapenv:Body>");
        source.append("<web:toTraditionalChinese>");
        source.append("<web:sText>").append(param).append("</web:sText>");
        source.append("</web:toTraditionalChinese>");
        source.append("</soapenv:Body>");
        source.append("</soapenv:Envelope>");
        StreamSource xmlSource = new StreamSource(new StringReader(source.toString()));
        
        URL wsdlURL = new URL(url);
        QName serviceQName = new QName(targetNamespace, "TraditionalSimplifiedWebService");
        Service service = Service.create(wsdlURL, serviceQName);
        QName portQName = new QName(targetNamespace, portName);
        Dispatch<Source> dispatch = service.createDispatch(portQName, Source.class, Service.Mode.MESSAGE);
        
        //.NET的服务端Soap1.1需要,不加会报错误:服务器未能识别 HTTP 头 SOAPAction 的值
        Map<String, Object> requestContext = dispatch.getRequestContext();
        requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
        requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese");
        
        Source orderSource = dispatch.invoke(xmlSource);
        StreamResult result = new StreamResult(new ByteArrayOutputStream());
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.transform(orderSource, result);
        ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
        String responseContent = new String(baos.toByteArray());
        System.out.println(responseContent);

        Reader file = new StringReader(responseContent);
        SAXReader reader = new SAXReader();
        Document dc = reader.read(file);
        //节点名称为toTraditionalChineseResult 命名空间为http://webxml.com.cn/
        String r = dc.selectSingleNode("//*[local-name()='toTraditionalChineseResult' and namespace-uri()='http://webxml.com.cn/']").getText().trim();
        System.out.println(r);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.1.3, the complete code

Information set in the code can be queried in preparation for, or in the WSDL or Soap message here is not to explain. The complete code is as follows:

package com.inspur.ws;

import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * JAX-WS Dispatch方式调用WebService样例
 * @author wuyy
 *
 */
public class JaxWsDispatch {
    private static String url = "http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl";
    private static String targetNamespace = "http://webxml.com.cn/";
    /**
     * dispatch Payload方式调用WebService
     * @param portName 端口名称
     * @param param 参数
     */
    public static void dispatchPayload(String portName, String param) {
        try {
            StringBuffer source = new StringBuffer();
            source.append("<web:toTraditionalChinese xmlns:web=\"" + targetNamespace + "\">");
            source.append("<web:sText>").append(param).append("</web:sText>");
            source.append("</web:toTraditionalChinese>");
            StreamSource xmlSource = new StreamSource(new StringReader(source.toString()));
            
            WsdlURL the URL = new new the URL (URL); 
            the QName serviceQName = new new the QName (the targetNamespace, "TraditionalSimplifiedWebService" ); 
            -Service-Service = Service.create (wsdlURL, serviceQName); 
            the QName portQName = new new the QName (the targetNamespace, the portName); 
            the Dispatch <the Source> dispatch service.createDispatch = (. portQName, Source class , Service.Mode.PAYLOAD); 
            
            // the .NET server-side Soap1.1 needed, without error will be reported: server failed to recognize the value of HTTP header SOAPAction 
            Map <String, Object > requestContext = dispatch.getRequestContext ();
            requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
            requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese");
            
            Source orderSource = dispatch.invoke(xmlSource);
            StreamResult result = new StreamResult(new ByteArrayOutputStream());
            Transformer trans = TransformerFactory.newInstance().newTransformer();
            trans.transform(orderSource, result);
            ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
            String responseContent = new String(baos.toByteArray());
            System.out.println(responseContent);

            Reader file = new StringReader(responseContent);
            SAXReader reader = new SAXReader();
            Document dc = reader.read(file);
            Element root = dc.getRootElement();
            String r = root.elementText("toTraditionalChineseResult").trim();
            System.out.println(r);

        } catch (Exception e) {
            e.printStackTrace();
        } 
    } 
    
    / ** 
     * Payload dispatch invoke the WebService 
     *@param namespace soapNamespace soap message of the entire message body, Soap1.1 different and Soap1.2 
     * @param the portName port name 
     * @param param parameter
      * / 
    public  static  void DispatchMessage (String soapNamespace, the portName String, String param) {
         the try { 
            the StringBuffer Source = new new the StringBuffer (); 
            source.append ( "<soapenv: Envelope xmlns: soapenv = \" "+ soapNamespace +" \ "xmlns: Web = \" "+ the targetNamespace +" \ ">" ); 
            Source. the append ( "<soapenv: Header />" ); 
            source.append ( "<soapenv:Body>");
            source.append("<web:toTraditionalChinese>");
            source.append("<web:sText>").append(param).append("</web:sText>");
            source.append("</web:toTraditionalChinese>");
            source.append("</soapenv:Body>");
            source.append("</soapenv:Envelope>");
            StreamSource xmlSource = new StreamSource(new StringReader(source.toString()));
            
            URL wsdlURL = new URL(url);
            ServiceQName the QName = newthe QName (the targetNamespace, "TraditionalSimplifiedWebService" ); 
            -Service-Service = Service.create (wsdlURL, serviceQName); 
            the QName portQName = new new the QName (the targetNamespace, the portName); 
            the Dispatch . <The Source> dispatch = service.createDispatch (portQName, the Source class , Service.Mode.MESSAGE); 
            
            // the .NET server-side Soap1.1 needed, without error will be reported: server failed to recognize the value of HTTP header SOAPAction of 
            the Map <String, Object> requestContext = dispatch.getRequestContext (); 
            requestContext .put (BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
            requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, "http://webxml.com.cn/toTraditionalChinese");
            
            Source orderSource = dispatch.invoke(xmlSource);
            StreamResult result = new StreamResult(new ByteArrayOutputStream());
            Transformer trans = TransformerFactory.newInstance().newTransformer();
            trans.transform(orderSource, result);
            ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
            String responseContent = new String(baos.toByteArray());
            System.out.println(responseContent);

            Reader file = new StringReader(responseContent);
            SAXReader reader = new SAXReader();
            Document dc = reader.read(file);
            //节点名称为toTraditionalChineseResult 命名空间为http://webxml.com.cn/
            String r = dc.selectSingleNode("//*[local-name()='toTraditionalChineseResult' and namespace-uri()='http://webxml.com.cn/']").getText().trim();
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
    
    Public  static  void main (String [] args) {
         // SOAP1.1 corresponding portName is TraditionalSimplifiedWebServiceSoap, Soap1.2 corresponding portName is TraditionalSimplifiedWebServiceSoap12 
        dispatchPayload ( "TraditionalSimplifiedWebServiceSoap", "Primary" ); 
        dispatchPayload ( "TraditionalSimplifiedWebServiceSoap12", "university " ); 
        
        // SOAP1.1 corresponding soapNamespace as HTTP: // schemas.xmlsoap.org/soap/envelope/,Soap1.1 corresponding soapNamespace as HTTP: // www.w3.org/2003/05/soap- Envelope 
        DispatchMessage ( "http://schemas.xmlsoap.org/soap/envelope/", "TraditionalSimplifiedWebServiceSoap", "school" );
        dispatchMessage( " http://www.w3.org/2003/05/soap-envelope ","TraditionalSimplifiedWebServiceSoap12", "大学");
    }

}
View Code

2.2, RPC way

RPC approach has not been recommended for use, service and client needs are JAVA, where the call is ready to work in the configuration of the local service; Xu ITestService the interface files are copied to the client works inside.

package com.inspur.ws;

import java.net.URL;

import javax.xml.ws.Service;

import com.inspur.zsyw.ws.ITestService;

/**
 * JAX-WS RPC调用 需要服务端、客户端都是JAVA
 * @author wuyy
 *
 */
public class JaxWsRpc {
    private static String url = "http://10.40.103.48:9006/zsywservice/TestService?wsdl";
    private static String targetNamespace = "http://ws.zsyw.inspur.com/";
    
    public static void rpc(String param) {
        try {
            javax.xml.namespace.QName qname = new javax.xml.namespace.QName(targetNamespace, "TestService");
            Service service = Service.create(new URL(url), qname);
            ITestService testService = service.getPort(ITestService.class);
            System.out.println(testService.hello(param));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        rpc("大学");
    }
}

 

 

Guess you like

Origin www.cnblogs.com/wuyongyin/p/11850797.html