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>
上一篇: 互联网技术之-误解
下一篇: 经期保养吃什么 经期药膳食疗方推荐