Java如何调用wsdl的webservice接口

java开发,当我们获取到了对方提供的wsdl地址,然后在网页上能够访问wsdl文档以后,如何调用对方的webservic呢?

一.首先了解下WSDL

WSDL(网络服务描述语言,Web Services Description Language)是一门基于 XML 的语言,用于描述 Web Services 以及如何对它们进行访问。

二.如何生成webService客户端去调用服务端

1.报存wsdl的xml文件:并将其后缀改为wsdl

2.把保存的 wsdl 文件加进项目,创建一个包,放在下面.

3.使用idea自带插件,Tools -> WebServices -> Generatte Java Code From Wsdl (这里有坑,idea版本低于2020的 没有WebServices) 

 

生成如下图:

生成是会加入依赖:

1
org.apache.cxfcxf-rt-frontend-jaxws3.1.11compile

这里涉及到 Spring整合CXF

三.客户端参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public static void main(String[] args) throws Exception {
        WebServiceConfig cfg = WebServiceConfig.getInstance();
        ISysNotifyTodoWebService service = (ISysNotifyTodoWebService) callService(cfg.getAddress(), cfg.getServiceClass());
        // 请在此处添加业务代码
        NotifyTodoContext context = new NotifyTodoContext();
        //数据格式要参考对方给的数据格式
        context.setSubject("测试待办webservice~~~");
        context.setLink("http://news.sina.com.cn/");
        context.setType(2);
        context.setKey("sinaNews");
        context.setModelId("123456789");
        context.setTargets("{"Id":"12fe2de141b7b97b32d1af34204a9f54"}");
        context.setOptTime("2022-01-25 09:25:09");
        NotifyTodoAppResult result = service.sendTodo(context);
        if (result != null) {
            if (result.getReturnState() != 2)
                System.out.println(result.getMessage());
        }
    }
  
    /**
      * 调用服务,生成客户端的服务代理
      *
      * @param address WebService的URL
      * @param serviceClass 服务接口全名
      * @return 服务代理对象
      * @throws Exception
      */
     public static Object callService(String address, Class serviceClass) throws Exception {
         JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
         // 记录入站消息
         factory.getInInterceptors().add(new LoggingInInterceptor());
         // 记录出站消息
         factory.getOutInterceptors().add(new LoggingOutInterceptor());
         // 添加消息头验证信息。如果服务端要求验证用户密码,请加入此段代码
         // factory.getOutInterceptors().add(new AddSoapHeader());
         factory.setServiceClass(serviceClass);
         factory.setAddress(address);
         // 使用MTOM编码处理消息。如果需要在消息中传输文档附件等二进制内容,请加入此段代码
         // Map props = new HashMap();
         // props.put("mtom-enabled", Boolean.TRUE);
         // factory.setProperties(props);
         // 创建服务代理并返回
         return factory.create();
     }

不同的环境(开发测试生产)注意修改 IP 和端口

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/11125.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部