webservice客户端(限java语言)

场景:服务端使用java语言编写
服务端暴露的接口: public String sayHi(String name);
客户端代码:
1.调用接口定义(和服务接口定义一致)

import javax.jws.WebMethod;
import javax.jws.WebService;
import java.util.List;

@WebService(targetNamespace = "http://webservice.trade.***.com/")
public interface RemoteWebService {

    @WebMethod
    public String sayHi(String name);

}

2.获取webservice客户端的工具类

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import java.util.HashMap;

/**
 * 用于获取webservice客户端
 */
public class WebServiceUtil {
    private WebServiceUtil() {
        throw new IllegalAccessError("CallWebServiceInterface class");
    }

    public static <E> E getWebServiceClient(String url, Class<E> clazz, int connectionTimeout, int receiveTimeout) {
        JaxWsProxyFactoryBean proxy = new JaxWsProxyFactoryBean();
        HashMap<String, Object> map = new HashMap<>();
        proxy.setServiceClass(clazz);
        proxy.setAddress(url);
        proxy.setProperties(map);
        @SuppressWarnings("unchecked")
        E client = (E) proxy.create();
        // 配置超时时间
        Client clientProxy = ClientProxy.getClient(client);
        HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(connectionTimeout); // 连接超时时间
        policy.setReceiveTimeout(receiveTimeout);// 请求超时时间
        conduit.setClient(policy);
        return client;
    }

    public static <E> E getWebServiceClient(String url, Class<E> clazz) {
        return getWebServiceClient(url, clazz, 5000, 5000);
    }
}

3.测试类

public class Test{

    public static void main(String[] args){
            // 第一个参数是webservice服务地址,第二个参数是接口调用定义类
            RemoteWebService remoteWebService = WebServiceUtil.getWebServiceClient("http://localhost:8080/phfund/trade/webservice/HelloWorld?wsdl", RemoteWebService.class);
            String result = remoteWebService.sayHi("xiaoming");
            System.out.println("结果" + result);

    }

}

4.maven依赖

      <!-- https://mvnrepository.com/artifact/org.apache.cxf/apache-cxf -->
      <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>apache-cxf</artifactId>
          <version>3.0.0</version>
          <type>pom</type>
          <exclusions>
              <exclusion>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-jdk14</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值