Java调用WebService接口的四种方式

使用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 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n" +
         "xmlns:wsi=\"http://xxx.webservice.xxx.com/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <wsi:GlobalFunc>\n" +
                "         <!--Optional:-->\n" +
                "         <param1>" + "参数1" + "</param1>\n" +
                "         <param2>" + "参数2"+ "</param2>\n" +
                "         <param3>" + "参数3"+ "</param3>\n" +
                "      </wsi:GlobalFunc>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        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注解方式调用

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

  • 1
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java调用WebService接口有多种方式,以下是其中两种常见的方式: 1. 使用JAX-WS (Java API for XML Web Services):JAX-WS是Java EE的一部分,它提供了一种简单的方式来开发和调用WebService接口。你可以使用wsimport工具根据WSDL(Web Services Description Language)文件生成客户端代码,并使用该代码调用WebService接口。下面是一个简单的示例代码: ```java import com.example.webservice.HelloWorld; import com.example.webservice.HelloWorldService; public class WebServiceClient { public static void main(String[] args) { HelloWorldService service = new HelloWorldService(); HelloWorld port = service.getHelloWorldPort(); String result = port.sayHello("John"); System.out.println(result); } } ``` 2. 使用Apache CXF:Apache CXF是一个开源的WebService框架,它提供了丰富的功能和灵活的配置选项。你可以使用CXF的工具生成客户端代码,并使用该代码调用WebService接口。下面是一个简单的示例代码: ```java import com.example.webservice.HelloWorld; public class WebServiceClient { public static void main(String[] args) { HelloWorld service = new HelloWorld(); HelloWorld port = service.getHelloWorldPort(); String result = port.sayHello("John"); System.out.println(result); } } ``` 这只是两种常见的方式之一,实际上还有其他的方式可以调用WebService接口,如使用Spring Web Services等。具体选择哪种方式取决于你的需求和项目的情况。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值