Bootstrap

Java程序调用.net提供的WebService

前言

Java调用WebService的相关资料,网上一搜一大把,但我这个遇见的比较特殊,所以记一下

正常的调用,推荐一个好用的工具

依赖

		<!-- hutool工具 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.4</version>
        </dependency>
// 新建客户端
SoapClient client = SoapClient.create("http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx")
    // 设置要请求的方法,此接口方法前缀为web,传入对应的命名空间
    .setMethod("web:getCountryCityByIp", "http://WebXml.com.cn/")
    // 设置参数,此处自动添加方法的前缀:web
    .setParam("theIpAddress", "218.21.240.106");

    // 发送请求,参数true表示返回一个格式化后的XML内容
    // 返回内容为XML字符串,可以配合XmlUtil解析这个响应
    Console.log(client.send(true));

hutool工具还有很多好用的工具,官网链接:
https://hutool.cn/docs/#/

参数不是键值对的,而是接收的数组的

我这里的情况显示报错, 后来是翻.net源码找到那个服务的方法, 发现它的参数是数组, org[0], org[1],org[2],不是我们一般用的JSON

依赖

		<!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.xml.rpc/javax.xml.rpc-api -->
        <dependency>
            <groupId>javax.xml.rpc</groupId>
            <artifactId>javax.xml.rpc-api</artifactId>
            <version>1.1.2</version>
        </dependency>

方法

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

import javax.xml.rpc.ParameterMode;
import java.util.List;

/**
 * @author gzh
 * @Classname WebServiceUtil
 * @Date 2022/1/10 14:43
 */
public class WebServiceUtil {
    /**
     * 请求WebService
     * @param nameSpace 命名空间
     * @param endpoint WebService的url
     * @param method 方法
     * @param params 参数,按顺序添加
     * @return
     */
    public static String webserviceFunction(String nameSpace, String endpoint, String method, List<String> params) {
        String result = null;
        Object[] parameter = new Object[params.size()];
        try {
            Service service = new Service();

            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(endpoint));
            call.setOperationName(new javax.xml.namespace.QName(nameSpace, method));//WSDL里面描述的接口名称
            for (int i = 0; i < params.size(); i++) {
                call.addParameter("arg" + i, XMLType.XSD_STRING, ParameterMode.IN);//接口的参数
                parameter[i] = params.get(i);
            }
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型
            call.setUseSOAPAction(true);
            call.setSOAPActionURI(nameSpace + method);
            result = (String) call.invoke(parameter);
            //给方法传递参数,并且调用方法
            System.out.println("result is :" + result);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }
}

;