最近在工作中需要用到cxf为印度某家公司提供的api去创建一个client,这样我们公司内部可以直接依赖client去调用那些api。做的过程中遭遇了好多坑,主要问题是自己能力不够... 网上有很多关于这方面的文章,但是因为我区分不到他们用的是SOAP,还是用的REST,所以导致了一些问题。
我们要调用的api是REST的,所以实现的时候需要用到JAXRSClientFactory去创建client,我在网上看到的很多代码都是用JaxWsProxyFactoryBean来创建client的,经测试,JaxWsProxyFactoryBean是用来为SOAP协议的,而非REST。
JAXRSClientFactory 和 JaxWsProxyFactoryBean 这两个类的差别就在这里。
已为REST api 创建client为例:还需设置网络代理去访问 fyi~
OrderApi.java 是一个接口,里面设置了patch delete post 方法:
@POST
@Path("/orders")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public PostResponse postOrders(PostOrdersRequest postOrdersRequest);
@PATCH
@Path("/orders")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public PatchResponse placeOrders(@NotEmpty @RequestBody PatchOrderRequest patchOrderRequest);
@DELETE
@Path("/orders/{OrderIds}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public GetOrderResponse deleteOrders(@QueryParam(value = "AccountKey") String accountKey, @PathParam(value = "OrderIds") String orderIds)
configure 类:
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider(objectMapper, DEFAULT_ANNOTATIONS));
// 用JAXRSClientFactory去为OrderApi设置代理类
OrderApi orderApiProxy = JAXRSClientFactory.create(saxoOrderApi, OrderApi.class, providers);
Client client = WebClient.client(orderApiProxy);
ClientConfiguration config = WebClient.getConfig(client);
HTTPConduit httpConduit = config.getHttpConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setProxyServer(proxyServer);
httpClientPolicy.setProxyServerPort(proxyPort);
httpConduit.setClient(httpClientPolicy);
ProxyAuthorizationPolicy proxyAuthorizationPolicy = new ProxyAuthorizationPolicy();
proxyAuthorizationPolicy.setUserName(username);
proxyAuthorizationPolicy.setPassword(password);
httpConduit.setProxyAuthorization(proxyAuthorizationPolicy);
TLSClientParameters tlsClientParameters = new TLSClientParameters();
tlsClientParameters.setDisableCNCheck(true);
//创建DumbX509TrustManager去忽略证书:DumbX509TrustManager类继承自 X509TrustManager
tlsClientParameters.setTrustManagers(new TrustManager[] { new
DumbX509TrustManager() });
httpConduit.setTlsClientParameters(tlsClientParameters);
AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setAuthorizationType("Bearer");
authorizationPolicy.setAuthorization(bearerToken);
httpConduit.setAuthorization(authorizationPolicy);
config.getInInterceptors().add(new LoggingInInterceptor());
config.getOutInterceptors().add(new LoggingOutInterceptor());