WebService接口的几种调用方式--wsdl文件类型

一般有几种方式调用此接口:

方式一:通过wsdl文件或者链接使用相关IDE软件生成Java文件

这种方式比较累赘,不做推荐,使用IDE软甲即可完成

方式二:使用apache的动态代理方式实现

import java.net.URL;
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class UsingDII {
    public static void main(String[] args) {
        try {
            int a = 100, b=60;
       // 对应的targetNamespace
            String endPoint = "http://198.168.0.88:6888/ormrpc/services/EASLogin";
            Service service = new Service();
            Call call = (Call)service.createCall();
            call.setOperationName(new QName(endPoint,"EASLogin"));
            call.setTargetEndpointAddress(new URL(endPoint));
       // a,b 调用此方法的参数
            String result = (String)call.invoke(new Object[]{new Integer(a),new Integer(b)});
            System.out.println("result is :"+result);        
        } catch (Exception e) {
            e.printStackTrace();
        }     
    }
}

方式三:使用Dynamic Proxy动态代理

import java.net.URL;
import javax.xml.*;
public class UsingDP {
    public static void main(String[] args) {
        try {
            int a = 100, b=60;
            String wsdlUrl = "http://198.168.0.88:6888/ormrpc/services/EASLogin?wsdl";
            String nameSpaceUri = "http://198.168.0.88:6888/ormrpc/services/EASLogin";
            String serviceName = "EASLoginProxyService";
            String portName = "EASLogin";
            ServiceFactory serviceFactory = ServiceFactory.newInstance();        
            Service service = serviceFactory.createService(new URL(wsdlUrl),new QName(nameSpaceUri,serviceName));
        // 返回值是自己封装的类
            AddFunctionServiceIntf adsIntf = (AddFunctionServiceIntf)service.getPort(new QName(nameSpaceUri,portName),AddFunctionServiceIntf.class);        
            System.out.println("result is :"+adsIntf.addInt(a, b));       
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 方式四:使用httpclient方式

 参考:java 调用wsdl的webservice接口 两种调用方式 - 綦霖 - 博客园icon-default.png?t=LA92https://www.cnblogs.com/yangchengdebokeyuan/p/11352950.html

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

// 这里引得依赖  包的话需要自己找了 下面地址可以找到
//https://mvnrepository.com/



public static InputStream postXmlRequestInputStream(String requestUrl, String xmlData) throws IOException{
        
        PostMethod postMethod = new PostMethod(requestUrl);
        byte[] b = xmlData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml;charset=utf-8");
        postMethod.setRequestEntity(re);
        
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getHostConfiguration().setProxy(CommonPptsUtil.get("PROXY_HOST"), Integer.valueOf(CommonPptsUtil.get("PROXY_PORT")));
        
        int statusCode = httpClient.executeMethod(postMethod);
        logger.debug("responseCode:"+statusCode);
        if (statusCode != 200) {
            return null;
        }
        return postMethod.getResponseBodyAsStream();
    }
    
    public static void main(String[] args) {
        String reqJsonStr = "{\"workId\":\"20171018161622\",\"status\":\"201\",\"startTime\":\"2017-10-18 16:16:22\"}";
        
        String xmlData =  "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.interfacemodule.cic.com/\"><soapenv:Header/><soapenv:Body><ser:statusWriteBack><jsonString>"
                + "{\"workId\":\"314\",\"orderId\":\"5207675\",\"longitude\":\"104.068310\",\"latitude\":\"30.539503\",\"sendTime\":\"2019-08-13 08:38:45\",\"servicePerName\":\"于xx\",\"servicePerPhone\":\"184xxxx7680\"}"
                + "</jsonString></ser:statusWriteBack></soapenv:Body></soapenv:Envelope>";
        String url = "http://xx.xxx.246.88:7103/avs/services/CCService?wsdl";
        SAXReader reader  = new SAXReader();
        String result = "";
        try {
            InputStream in = postXmlRequestInputStream(url,xmlData);
            if(in!=null){
                Document doc = reader.read(in);
                result = doc.getRootElement().element("Body").element("statusWriteBackResponse").element("return").getText();
                logger.debug("result:"+result);
            }
        } catch (Exception e) {
            logger.error("error:",e);
            e.printStackTrace();
        }
    }
}

 CommonPptsUtil://就是获取配置文件里的代理信息

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;

/**
 * 通用属性文件工具类
 * 
 * @author y.c
 * 
 */
public class CommonPptsUtil {

    private static final Logger logger = Logger.getLogger(CommonPptsUtil.class);

    private static final String CONFIG_FILE = "common.properties";

    private static PropertiesConfiguration ppts;

    static {
        try {
            ppts = new PropertiesConfiguration(CONFIG_FILE);
            ppts.setReloadingStrategy(new FileChangedReloadingStrategy());
        } catch (ConfigurationException e) {
            logger.error("文件【common.properties】加载失败!");
            ppts = null;
        }
    }

    /**
     * 获取属性值
     * 
     * @param key
     * @return 属性值
     */
    public static String get(String key) {
        if (ppts == null) {
            return null;
        }

        return ppts.getString(key);
    }
}

 

方式五:使用CXF动态调用webservice接口

代码如下:参考: cxf动态调用webservice接口_itdragons的博客-CSDN博客_cxf动态调用webserviceicon-default.png?t=LA92https://blog.csdn.net/itdragons/article/details/75390756

package cxfClient;
  
import org.apache.cxf.endpoint.Endpoint;
import javax.xml.namespace.QName; 
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
  
public class CxfClient {
  
    public static void main(String[] args) throws Exception {
        String url = "http://localhost:9091/Service/SayHello?wsdl";
        String method = "say";
        Object[] parameters = new Object[]{"我是参数"};
        System.out.println(invokeRemoteMethod(url, method, parameters)[0]);
    }
     
    public static Object[] invokeRemoteMethod(String url, String operation, Object[] parameters){
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!url.endsWith("wsdl")) {
            url += "?wsdl";
        }
        org.apache.cxf.endpoint.Client client = dcf.createClient(url);
        //处理webService接口和实现类namespace不同的情况,CXF动态客户端在处理此问题时,会报No operation was found with the name的异常
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(),operation);
        BindingInfo bindingInfo= endpoint.getEndpointInfo().getBinding();
        if(bindingInfo.getOperation(opName) == null){
            for(BindingOperationInfo operationInfo : bindingInfo.getOperations()){
                if(operation.equals(operationInfo.getName().getLocalPart())){
                    opName = operationInfo.getName();
                    break;
                }
            }
        }
        Object[] res = null;
        try {
            res = client.invoke(opName, parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }  
}

 

复制代码

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache CXF是一个开源的WebService框架,可以帮助用户快速、简便地开发和部署WebService应用程序。它提供了多种方式调用WebService接口,下面介绍几种常用的方式: 1. 使用JAX-WS API:CXF实现了JAX-WS API,可以直接使用JAX-WS提供的API来调用WebService。示例代码如下: ```java HelloWorldService service = new HelloWorldService(); HelloWorld port = service.getHelloWorldPort(); String result = port.sayHello("CXF"); ``` 2. 使用代理方式:CXF可以根据WebService WSDL文件自动生成代理类,然后通过调用代理类的方法来调用WebService接口。示例代码如下: ```java JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(HelloWorld.class); factory.setAddress("http://localhost:8080/HelloWorld"); HelloWorld client = (HelloWorld) factory.create(); String result = client.sayHello("CXF"); ``` 3. 使用Spring配置文件:CXF提供了Spring配置文件方式来实现WebService接口调用。用户可以在Spring配置文件中配置WebService客户端,然后通过Spring容器来获取WebService客户端实例。示例代码如下: ```xml <jaxws:client id="helloClient" serviceClass="com.example.HelloWorld" address="http://localhost:8080/HelloWorld"/> ``` ```java ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); HelloWorld client = (HelloWorld) context.getBean("helloClient"); String result = client.sayHello("CXF"); ``` 以上是几种常用的调用WebService接口方式,可以根据具体情况选择适合自己的方式

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值