JAVA 调WebServiceUtils工具类

本文介绍了一个用于简化Java中WebService调用的工具类WebServiceUtils,它基于Apache Axis和HttpClient,支持SOAP1.1和SOAP1.2调用。通过示例代码展示了如何使用该工具类进行远程Web服务通信,降低网络通信和报文构建的复杂性。

 

使用 Java 发起 WebService 调用的完美工具类解析与实例

在现代软件开发中,与远程 Web 服务进行交互是一个普遍的需求。Java 语言为此提供了丰富的工具和库。本文将详细介绍一个强大的工具类 WebServiceUtils,它是一个能够简化 WebService 调用的利器。我们将逐步解析该工具类,并通过示例演示如何使用它。

什么是 WebServiceUtils?

WebServiceUtils 是一个高效的工具类,为 Java 开发者提供了便捷的方式来发起 WebService 调用。该工具类借助 Apache Axis 和 Apache HttpClient 等库的功能,帮助我们构建并发送 SOAP 请求,从而与远程 Web 服务进行通信。

使用的依赖库

在使用 WebServiceUtils 之前,确保在项目的 pom.xml 文件中添加了以下依赖项:

<dependencies>
 <dependency>
  <groupId>commons-discovery</groupId>
  <artifactId>commons-discovery</artifactId>
  <version>0.5</version>
 </dependency>
 <dependency>
   <groupId>wsdl4j</groupId>
   <artifactId>wsdl4j</artifactId>
   <version>1.6.3</version>
 </dependency>
 <dependency>
   <groupId>org.apache.axis</groupId>
   <artifactId>axis</artifactId>
   <version>1.4</version>
 </dependency>
 <dependency>
  <groupId>javax.xml.rpc</groupId>
  <artifactId>javax.xml.rpc-api</artifactId>
  <version>1.1.1</version>
 </dependency>
</dependencies>

方法一:SOAP1.1 调用

WebServiceUtils.sendSoap11方法,用于发起 SOAP1.1 调用。以下是示例代码:

try {
    String userName = "yourUsername";
    String passWord = "yourPassword";
    String wsdlurl = "http://example.com/your-service";
    String soapXml = "<soapenv:Envelope..."; // 根据实际 SOAP 报文填写
    String soapAction = "yourSoapAction";
    
    String result = WebServiceUtils.sendSoap11(userName, passWord, wsdlurl, soapXml, soapAction);
    // 处理返回结果...
} catch (Exception e) {
    e.printStackTrace();
}

方法二:SOAP1.2 调用

WebServiceUtils.sendSoap12方法,用于发起 SOAP1.2 调用。以下是示例代码:

try {
    String wsdlurl = "http://example.com/your-service.wsdl";
    String method = "yourMethod";
    String targetNamespace = "http://example.com/namespace";
    Object[] keys = new Object[]{"param1", "param2"};
    Object[] values = new Object[]{"value1", "value2"};
    
    String[] result = WebServiceUtils.sendSoap12(wsdlurl, method, targetNamespace, keys, values);
    // 处理返回结果...
} catch (Exception e) {
    e.printStackTrace();
}

 JAVA 调WebServiceUtils工具类

package com.adapter.http.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName WebServiceUtils
 * @Description
 * @Author manhengwei
 * @Date 2021/8/10 6:06 下午
 * @Version 1.0
 **/
@Slf4j
public class WebServiceUtils {

    /**
     * 请求超时时间
     */
    private static final int SOCKET_TIMEOUT = 30000;

    /**
     * 传输超时时间
     */
    private static final int CONNECT_TIMEOUT = 30000;

    /**
     * 使用SOAP1.1发送消息
     *
     * @param wsdlurl    wsdl地址
     * @param soapXml    soap报文
     * @param soapAction soapAction
     * @return webService结果
     */
    public static String sendSoap11(String userName, String passWord, String wsdlurl, String soapXml, String soapAction) {
        String result = "";
        CloseableHttpClient closeableHttpClient = null;
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            closeableHttpClient = httpClientBuilder.build();
            HttpPost httpPost = new HttpPost(wsdlurl);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            httpPost.setHeader("Connection", "Keep-Alive");

            if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(passWord)) {
                String auth = userName + ":" + passWord;
                byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
                String basic = "Basic " + new String(encodedAuth);
                httpPost.setHeader("Authorization", basic);
            }

            StringEntity stringEntity = new StringEntity(soapXml, StandardCharsets.UTF_8);
            httpPost.setEntity(stringEntity);

            try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost)) {
                HttpEntity httpEntity = response.getEntity();
                if (httpEntity != null) {
                    result = EntityUtils.toString(httpEntity, "UTF-8");
                }
            }
        } catch (Exception e) {
            log.error("Exception in SOAP1.1 failed to send message!");
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (Exception e) {
                log.error("Exception in SOAP1.1 failed to closeableHttpClient!");
            }
        }

        return result;
    }

    /**
     * 调用WebService接口,AXIS方式直接引用远程的.wsdl文件
     * 调用接口时,传入方法名,字段与字段值顺序需要严格按照接口定义
     * 使用SOAP1.2发送消息
     *
     * @param wsdlurl         接口地址
     * @param method          方法名
     * @param keys            字段(方法参数)
     * @param values          字段值(参数对应值)
     * @param targetNamespace 命名空间
     * @return 接口返回值
     */
    public static String[] sendSoap12(String wsdlurl, String method, String targetNamespace, Object[] keys, Object[] values) throws Exception {

        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setEncodingStyle("UTF-8");
        call.setTargetEndpointAddress(wsdlurl);
        call.setOperationName(new QName(targetNamespace, method)); // 方法名称
        call.setReturnType(XMLType.SOAP_ARRAY);// 设置返回类型
        call.setReturnClass(String[].class);
        params(targetNamespace, call, keys, values);
        call.setUseSOAPAction(true);
        call.setSOAPActionURI(targetNamespace + method);
        return (String[]) call.invoke(values);

    }

    /**
     * 调用WebService接口之前,方法参数及参数赋值
     * 当前接口中参数类型仅限于字符串、整数、布尔,参数为空的情况为字符串类型
     *
     * @param targetNamespace 命名空间
     * @param call            接口访问请求
     * @param keys            字段(方法参数)
     * @param values          字段值(参数对应值)
     */
    private static void params(String targetNamespace, Call call, Object[] keys, Object[] values) {

        if (keys == null || values == null) {
            return;
        }
        if (keys.length == 0 || values.length == 0) {
            return;
        }
        if (keys.length != values.length) {
            throw new IllegalArgumentException("接口方法参数与参数值不匹配!");
        }
        for (int i = 0; i < values.length; i++) {
            String key = (String) keys[i]; //方法参数
            Object value = values[i]; //参数值
            if (value == null) {
                call.addParameter(new QName(targetNamespace, key), XMLType.XSD_STRING, ParameterMode.IN);
            } else if (value instanceof String) {
                call.addParameter(new QName(targetNamespace, key), XMLType.XSD_STRING, ParameterMode.IN);
            } else if (value instanceof Integer) {
                call.addParameter(new QName(targetNamespace, key), XMLType.XSD_INTEGER, ParameterMode.IN);
            } else if (value instanceof Boolean) {
                call.addParameter(new QName(targetNamespace, key), XMLType.XSD_BOOLEAN, ParameterMode.IN);
            }
        }
    }

}

总结

通过 WebServiceUtils,我们可以轻松地发起 SOAP1.1 和 SOAP1.2 调用,与远程 Web 服务进行通信。该工具类封装了底层的细节,让开发人员能够专注于业务逻辑的实现,而无需过多关注网络通信和报文构建。因此,它在现代 Java 项目中发起 WebService 调用时,是一个不可或缺的工具。

希望这篇博客能够帮助您更好地理解和使用 WebServiceUtils 工具类,以及如何利用它来与远程 Web 服务进行交互。如果您有任何疑问或建议,欢迎在下方留言与我们分享!

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值