Java调用WebService接口的几种方式

调用WebService

      • 使用wsimport生成代码(不推荐)
      • 使用Axis-1.4 动态调用
      • 使用HTTP+SOAP方式远程调用
      • 通过Spring注解方式调用

使用wsimport生成代码(不推荐)

配置java环境变量后在命令窗口中输入
-keep:是否生成java源文件

-d:指定.class文件的输出目录

-s:指定.java文件的输出目录

-p:定义生成类的包名,不定义的话有默认包名

-verbose:在控制台显示输出信息

-b:指定jaxws/jaxb绑定文件或额外的schemas

-extension:使用扩展来支持SOAP1.2

wsimport -encoding utf-8 -s D:\存放目录\ -p com.ws.cli -XadditionalHeaders -verbose  http://localhost/xxxx/xxxx?wsdl

即可生成Java代码,然后将代码拷贝到项目中,直接调用即可。
但这样生成的代码不够灵活,如果对方接口参数修改了,需要重新生成代码,不建议使用

使用Axis-1.4 动态调用

代码中使用的axis版本为1.4,需要注意的是不同版本的Axis相差很大,下面是调用代码

/**
     * Axis动态调用wsdl
     *
     * @param wsdlUrl             服务地址
     * @param targetNamespace     服务命名空间
     * @param operationMethodName 接口方法名
     * @param bodyParams          body参数 <参数名,参数值>
     * @param headerParams        header参数 <参数名,参数值> (可为空)
     * @param loadPart            loadPart(设置header时才需要)
     * @return T
     */
    public static <T> T invokeWebservice_axis(String wsdlUrl, String targetNamespace,
                                              String operationMethodName,
                                              Map<String, Object> bodyParams,
                                              Map<String, String> headerParams,
                                              String loadPart) {
        try {
            //引用远程的wsdl文件
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(wsdlUrl);
            //接口名
            call.setOperationName(new QName(targetNamespace, operationMethodName));
            //由于需要认证,故需要设置头部调用的密钥
            if (headerParams != null && headerParams.size() > 0) {
                SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement(targetNamespace, loadPart);
                soapHeaderElement.setNamespaceURI(targetNamespace);
                Set<Map.Entry<String, String>> headParamSet = headerParams.entrySet();
                for (Map.Entry<String, String> map : headParamSet) {
                    try {
                        soapHeaderElement.addChildElement(map.getKey()).setValue(map.getValue());
                    } catch (SOAPException e) {
                        e.printStackTrace();
                    }
                }
                call.addHeader(soapHeaderElement);
            }
            Object[] params = new Object[bodyParams.size()];
            //参数
            Set<Map.Entry<String, Object>> entries = bodyParams.entrySet();
            int i = 0;
            for (Map.Entry<String, Object> map : entries) {
                call.addParameter(new QName(targetNamespace, map.getKey()), XMLType.XSD_STRING, ParameterMode.IN);
                params[i] = map.getValue();
                i++;
            }
            // 设置返回类型
            call.setReturnType(XMLType.XSD_STRING);
            //传递参数,并且调用方法
            String result = (String) call.invoke(params);
            return (T) result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

使用HTTP+SOAP方式远程调用

需要使用工具SoapUI, 创建测试项目,得到具体方法名和参数名

/**
     * 通过SOAP调用WebService
     *
     * @param uri             address
     * @param soapRequestData soap表头
     * @param nodeName        返回信息的节点名
     * @return 指定节点的值
     */
    private static SAXReader reader = new SAXReader();
    public static String invokeWebservice_soap(String uri, String soapRequestData, String nodeName) {
        try {
            String method = uri;
            PostMethod postMethod = new PostMethod(method);
            byte[] b = soapRequestData.getBytes(StandardCharsets.UTF_8);
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml;charset=utf-8");
            postMethod.setRequestHeader("SOAPAction", "");
            postMethod.setRequestEntity(re);
            HttpClient httpClient = new HttpClient();
            Integer statusCode = httpClient.executeMethod(postMethod);
            byte[] responseBody = postMethod.getResponseBody();
            Document document = reader.read(new ByteArrayInputStream(responseBody));
            Map<String, String> nodeMap = new HashMap<>();
            getChildNodes(document.getRootElement(), nodeMap);
            return nodeMap.get(nodeName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

soapRequestData :通过SoapUI获取报文,拼接需要传递的参数
调用示例如下:

String soapRequestData = " +
         "xmlns:wsi=\"http://xxx.webservice.xxx.com/\">\n" +
                "   \n" +
                "   \n" +
                "      \n" +
                "         \n" +
                "         " + "参数1" + "\n" +
                "         " + "参数2"+ "\n" +
                "         " + "参数3"+ "\n" +
                "      \n" +
                "   \n" +
                "";
        WsdlClient.invokeWebservice_soap("http://xx/Service?wsdl", soapRequestData);

避免使用过程中出现类、参数等错误,代码中使用的类路径如下,直接Ctrl + C

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.soap.SOAPException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

通过Spring注解方式调用

代码比较简单,就不写了
链接: 注解方式调用.

你可能感兴趣的:(Java)