Java如何调用WebService方法呢?

戚薇 Java经验 发布时间:2023-06-04 09:11:08 阅读数:13472 1
下文笔者讲述java代码中调用WebService的方法分享,如下所示

Java调用WebService的实现思路

在java中
   我们可使用JAX-WS(Java API for XML Web Services)调用WebService
   此种调用方式无需引入其他jar包,都是jdk自带的功能 

实现思路:
  1.定义一个xml的webService消息
  2.传入soap消息即可
  3.接收返回的内容即可
例:Payload方式调用WebService
/**
 * 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()));
        
        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.PAYLOAD);
        
        //.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);
        Element root = dc.getRootElement();
        String r = root.elementText("toTraditionalChineseResult").trim();
        System.out.println(r);

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

Message方式调用WebService

  
/**
 * dispatch Payload方式调用WebService
 * @param soapNamespace soap消息整个消息体的命名空间,Soap1.1和Soap1.2不一样
 * @param portName 端口名称
 * @param param 参数
 */
public static void dispatchMessage(String soapNamespace, String portName, String param) {
    try {
        StringBuffer source = new StringBuffer();
        source.append("<soapenv:Envelope xmlns:soapenv=\"" + soapNamespace + "\" xmlns:web=\"" + 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();
    }
}

Proxy方式调用webService

接口类ITestService拷贝到客户端工程里。调用本地服务如下:

 package com.java265.ws;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.java265.ITestService;

/**
 * JAX-WS Proxy调用 ,需把接口类拷贝到客户端
 *
 */
public class JaxWsProxy {
    private static String url = "http://****:81/testwservice/TestService?wsdl";
    private static String targetNamespace = "http://java265.com/";
    
    public static void proxy(String param) {
        try {
            QName qname = new 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) {
        proxy("Java是我最爱的开发语言");
    }
}

RPC方式

package com.java265.ws;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;

import com.java265.ITestService;

/**
 * JAX-WS RPC调用 ,需把接口类拷贝到客户端,接口类需继承java.rmi.Remote接口
 *
 */
public class JaxWsRpc {
    private static String url = "http://****:81/wservice/TestService?wsdl";
    private static String targetNamespace = "http://java265.com/";
    
    public static void rpc(String param) {
        try {
            ServiceFactory serviceFactory = ServiceFactory.newInstance();
            Service service = serviceFactory.createService(new URL(url), new QName(targetNamespace, "TestService"));
            ITestService testService = (ITestService) service.getPort(ITestService.class);
            String result = testService.hello(param);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        rpc("java是我最爱的开发语言");
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16858411026705.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者