java使用CXF动态调用webservice接口

 

 1 package com.webservice.client.config;
 2 
 3 import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
 4 import javax.xml.namespace.QName;
 5 
 6 /**
 7  * @author liuwenlong
 8  * @create 2022-02-20 11:20:13
 9  */
10 @SuppressWarnings("all")
11 public class CxfClientTester {
12 
13     public static final String serviceUrl = "http://地址/api/insertUserInfo?wsdl";
14     public static final String methodName = "insertUserInfo";
15     public static final String nameSpaceUrl = "http://service.api.spring.com/";
16     public static final String param = "请求xml";
17 
18     public static void main(String[] args) throws Exception {
19         try {
20             System.out.println("反馈结果:" + webserviceInterface(serviceUrl, nameSpaceUrl, methodName, param));
21         } catch (Exception e) {
22             System.out.println("ERROR:" + e.getMessage());
23         }
24     }
25 
26     public static String webserviceInterface(String serviceUrl, String nameSpaceUrl, String methodName, String param) throws Exception {
27         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
28         org.apache.cxf.endpoint.Client client = dcf
29                 .createClient(serviceUrl);
30         // url为调用webService的wsdl地址
31         QName name = new QName(nameSpaceUrl, methodName);
32         // namespace是命名空间,methodName是方法名
33         String xmlStr = param;
34         // paramvalue为参数值
35         Object[] objects;
36         try {
37             objects = client.invoke(name, xmlStr);
38             return objects[0].toString().toString();
39         } catch (Exception e) {
40             e.printStackTrace();
41         }
42         return "";
43     }
44 }

 

或者,将反馈对象转为json

 1     public static void main(String[] args) throws Exception {
 2         try {
 3             String userInterfaceURL = "http://localhost:8081/userInfterface?wsdl";
 4 
 5             JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
 6             Client client = dcf.createClient(userInterfaceURL);
 7 
 8             Object[] objects=client.invoke("insertUser", "test");
 9             //输出调用结果
10             System.out.println(JSONObject.toJSONString(objects));
11         } catch (Exception e) {
12             System.out.println("ERROR:" + e.getMessage());
13         }
14     }

 

posted @ 2022-02-20 11:56  勤快的懒羊羊  阅读(2048)  评论(0编辑  收藏  举报