欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webservice客户端(限java语言)

程序员文章站 2022-06-06 09:35:09
...

场景:服务端使用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>
相关标签: webservice客户端