如何使用 httpClient4 为 Axis2 配置 SSL [英] How to configure SSL with Axis2 using httpClient4

查看:75
本文介绍了如何使用 httpClient4 为 Axis2 配置 SSL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 httpClient 3 已经过时,我需要替换代码:

SSLProtocolSocketFactory.setSSL(trustStore, keyStore, pasw);ProtocolSocketFactory factory = new SSLProtocolSocketFactory();Protocol.registerProtocol("https", new Protocol("https", factory, 443));

如果有人尝试过,请分享.

在java代码中,我尝试使用OperationClient对象调用webserviceoperationClientObject.execute(true);

提前致谢..

解决方案

axis2 httpclient4 迁移并不是那么容易,正如从文档"中看到的那样.

在此过程中,我使用了最新的 Axis 2 版本 1.7.8.

轴 2 1.7.0 发行说明 包含一个单行,用于 HttpClient v4 集成:

Axis2 1.7.0 除了不再维护的 Commons HttpClient 3.x 之外,还支持 Apache HttpClient 4.x.要启用对 HttpClient 4.x 的支持,请在 axis2.xml 中使用 org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender 而不是 org.apache.axis2.transport.http.CommonsHTTPTransportSender.请注意,代码是为 HttpClient 4.2.x 编写的,应该适用于 4.3.x 和 4.4.x,但与 4.5.x 不兼容.

注意最后一句话.Axis 2 1.7.8 pom 文件,二进制分发版包含 httpclient-4.5.3.jar,但不能使用它.因此,请改用 httpclient 4.4.1.

启用日志记录

在升级之前,我想您已经有一个工作轴 2 项目.我建议启用轴 2 调试日志记录,看看会发生什么.要启用日志记录,请使用 jvm 参数定义自定义 log4j 属性文件:

-Dlog4j.configuration=file:/c:/work/sources/debug_log4j.properties

debug_log4j.properties 文件的内容是:

log4j.rootCategory=调试,控制台log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayoutlog4j.appender.CONSOLE.layout.ConversionPattern=[%p] %m%n

Axis2 + Httpclient4

如果你没有axis2.xml,你可以在axis2中找到它二进制包(包含所有依赖项和示例配置)

根据发行说明,您需要将传输发送器从 CommonsHTTPTransportSender 更改为 HTTPClient4TransportSender.

如果您查看(或调试)axis2 配置器,您会看到,xml 必须包含特定部分,否则axis2 不会读取它.

所以我配置为使用 HttpClient4 后的axis2.xml 内容(并删除了未使用的部分,但保留了必要的部分):

<!-- ================================================ --><!-- 运输输出--><!-- ================================================ --><parameter name="hotdeployment">true</parameter><参数名称="热更新">false</parameter><parameter name="enableMTOM">false</parameter><参数名称="enableSwA">false</parameter><transportSender name="local"class="org.apache.axis2.transport.local.LocalTransportSender"/><transportSender name="http"class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender"><参数名称="PROTOCOL">HTTP/1.1</parameter><parameter name="Transfer-Encoding">chunked</parameter><!-- 如果以下设置为true",则不会将 Content-Type 的可选操作部分添加到 SOAP 1.2 消息中 --><!-- <parameter name="OmitSOAP12Action">true</parameter>--></transportSender><transportSender name="https"class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender"><参数名称="PROTOCOL">HTTP/1.1</parameter><parameter name="Transfer-Encoding">chunked</parameter></transportSender><!-- ================================================ --><!-- 阶段--><!-- ================================================ --><phaseOrder type="InFlow"><!-- 系统预定义阶段--><阶段名称=运输"><处理程序名称="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"><order phase="运输"/></处理程序><handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"><order phase="运输"/></处理程序><阶段名称="寻址"><handler name="AddressingBasedDispatcher"class="org.apache.axis2.dispatchers.AddressingBasedDispatcher"><order phase="寻址"/></处理程序><阶段名称=安全"/><阶段名称="PreDispatch"/><phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"><handler name="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/><handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/><handler name="RequestURIOperationDispatcher"class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/><handler name="SOAPMessageBodyBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/><handler name="HTTPLocationBasedDispatcher"class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/><handler name="GenericProviderDispatcher"class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/><handler name="MustUnderstandValidationDispatcher"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/><阶段名称="RMPhase"/><!-- 系统预定义阶段--><!-- 在 Postdispatch 阶段之后,模块作者或服务作者可以添加他想要的任何阶段 --><阶段名称="OperationInPhase"><处理程序名称="MustUnderstandChecker"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandChecker"><order phase="OperationInPhase"/></处理程序><phase name="soapmonitorPhase"/></phaseOrder><phaseOrder type="OutFlow"><!-- 用户可以将他自己的阶段添加到该区域--><phase name="soapmonitorPhase"/><阶段名称="OperationOutPhase"/><!--系统预定义阶段--><!--无论服务如何,这些阶段都将运行--><阶段名称="RMPhase"/><阶段名称="PolicyDetermination"/><阶段名称=MessageOut"/><阶段名称=安全"/></phaseOrder><phaseOrder type="InFaultFlow"><阶段名称="寻址"><handler name="AddressingBasedDispatcher"class="org.apache.axis2.dispatchers.AddressingBasedDispatcher"><order phase="寻址"/></处理程序><阶段名称=安全"/><阶段名称="PreDispatch"/><phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"><handler name="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/><handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/><handler name="RequestURIOperationDispatcher"class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/><handler name="SOAPMessageBodyBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/><handler name="HTTPLocationBasedDispatcher"class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/><handler name="GenericProviderDispatcher"class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/><handler name="MustUnderstandValidationDispatcher"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/><阶段名称="RMPhase"/><!-- 用户可以将他自己的阶段添加到该区域--><阶段名称="OperationInFaultPhase"/><phase name="soapmonitorPhase"/></phaseOrder><phaseOrder type="OutFaultFlow"><!-- 用户可以将他自己的阶段添加到该区域--><phase name="soapmonitorPhase"/><阶段名称="OperationOutFaultPhase"/><阶段名称="RMPhase"/><阶段名称="PolicyDetermination"/><阶段名称=MessageOut"/><阶段名称=安全"/></phaseOrder></axisconfig>

在java端,需要创建自定义axis2配置上下文,以使用我们自定义的axis2.xml.Axis2 提供多种配置器,我更喜欢基于文件的配置器:

final ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("c:\\work\\sources\\axis2conf","c:\\work\\sources\\axis2conf\\axis2.xml");

您可以在构造函数期间将配置上下文分配给客户端存根:

FileNet_UploadDocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");

因此,如果您不想使用自定义 ssl 设置,则升级已完成.

Axis2 + Httpclient4 + SSL

升级到 httpclient4 后,实现不再使用自定义协议处理程序属性 (HTTPConstants.CUSTOM_PROTOCOL_HANDLER).

org/apache/axis2/transport/http/impl/httpclient3/HTTPSenderImpl.java:524 中的旧实现:

//可能需要设置自己的套接字工厂.让我们允许这种情况//也是.协议 protocolHandler = (Protocol) msg​​Ctx.getOptions().getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);

新实现 org/apache/axis2/transport/http/impl/httpclient4/HTTPSenderImpl.java:583:

//TODO : 一个人可能需要设置他自己的套接字工厂.我们也必须允许这种情况.

您需要在 httpclient4 端设置 ssl 上下文.这不是问题,因为轴允许您使用 HTTPConstants.CACHED_HTTP_CLIENT 属性为 ws 调用定义 httpclient:

options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

但是如果您为标准方式创建一个 httpclient4:

<预><代码>...HttpClientBuilder 构建器 = HttpClientBuilder.create();...

并将其分配给axis2 客户端存根,您得到一个ClassCastException,因为所有新的httpclient Builder、工厂等方法都基于ClosableHttpClient 创建了httpclient 的现代"实现.但是axis2 实现依赖于已弃用的AbstractHttpClient.所以你需要创建旧版本的httpclient.

完整示例:

import java.io.File;导入 java.io.FileInputStream;导入 java.io.InputStream;导入 java.net.URL;导入 java.nio.file.Files;导入 java.security.KeyStore;导入 java.security.SecureRandom;导入 java.security.Security;导入 javax.net.ssl.KeyManagerFactory;导入 javax.net.ssl.SSLContext;导入 javax.net.ssl.TrustManagerFactory;导入 org.apache.axis2.client.Options;导入 org.apache.axis2.client.ServiceClient;导入 org.apache.axis2.context.ConfigurationContext;导入 org.apache.axis2.context.ConfigurationContextFactory;导入 org.apache.axis2.transport.http.HTTPConstants;导入 org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory;导入 org.apache.http.client.HttpClient;导入 org.apache.http.config.Registry;导入 org.apache.http.config.RegistryBuilder;导入 org.apache.http.conn.ClientConnectionManager;导入 org.apache.http.conn.scheme.Scheme;导入 org.apache.http.conn.scheme.SchemeRegistry;导入 org.apache.http.conn.socket.ConnectionSocketFactory;导入 org.apache.http.conn.socket.PlainConnectionSocketFactory;导入 org.apache.http.conn.ssl.DefaultHostnameVerifier;导入 org.apache.http.conn.ssl.SSLConnectionSocketFactory;导入 org.apache.http.conn.ssl.SSLSocketFactory;导入 org.apache.http.conn.ssl.TrustSelfSignedStrategy;导入 org.apache.http.impl.client.AbstractHttpClient;导入 org.apache.http.impl.client.CloseableHttpClient;导入 org.apache.http.impl.client.DefaultHttpClient;导入 org.apache.http.impl.client.HttpClientBuilder;导入 org.apache.http.impl.client.HttpClients;导入 org.apache.http.impl.conn.BasicClientConnectionManager;导入 org.apache.http.impl.conn.PoolingHttpClientConnectionManager;导入 org.apache.http.impl.conn.SingleClientConnManager;导入 org.apache.http.ssl.SSLContexts;公共类 SslTest {公共 SslTest() {//TODO 自动生成的构造函数存根}public static void main(String[] args) 抛出异常 {File keyFile = new File("c:\\work\\sources\\ConsoleApp25\\avp-pc.jks");最终 ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("c:\\work\\sources\\axis2conf","c:\\work\\sources\\axis2conf\\axis2.xml");FileNet_UploadocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");FileNet_UploadDocument wsMethodReq = new FileNet_UploadDocument();ServiceClient serviceClient = stub._getServiceClient();选项 options = serviceClient.getOptions();//密钥库类型:https://docs.oracle.com/javase/9​​/docs/specs/security/standard-names.html#keystore-typesKeyStore keyStore = KeyStore.getInstance("jks");InputStream in = null;尝试 {in = new FileInputStream(keyFile);keyStore.load(in, "changeit".toCharArray());} 最后 {如果(在!= null){附寄();}}//工厂实例类型:https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#T5//在 IBM 服务器上使用 IbmX509 而不是 SunX509KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");keyManagerFactory.init(keyStore, "changeit".toCharArray());TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");trustManagerFactory.init(keyStore);SSLContext sslContext = SSLContext.getInstance("TLSv1.2");sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());SSLSocketFactory sf = 新 SSLSocketFactory(sslContext);Scheme httpsScheme = new Scheme("https", 443, sf);SchemeRegistry schemeRegistry = new SchemeRegistry();schemeRegistry.register(httpsScheme);ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);HttpClient httpClient = new DefaultHttpClient(cm);options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);stub.fileNet_UploadDocument(wsMethodReq);System.out.println("完成");}

Since the httpClient 3 has been outdated, I need a replacement for the code:

SSLProtocolSocketFactory.setSSL(trustStore, keyStore, pasw);
ProtocolSocketFactory factory = new SSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", factory, 443));

Please share if anyone has tried it.

In the java code, I'm tring to call the webservice using OperationClient object operationClientObject.execute(true);

Thanks in advance..

解决方案

The axis2 httpclient4 migration is not so easy, as it appears from the "documentation".

During the process, I use the latest Axis 2 version 1.7.8.

The axis 2 1.7.0 release notes contains a one liner, for HttpClient v4 integration:

Axis2 1.7.0 supports Apache HttpClient 4.x in addition to the no longer maintained Commons HttpClient 3.x. To enable the support for HttpClient 4.x, use org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender instead of org.apache.axis2.transport.http.CommonsHTTPTransportSender in axis2.xml. Please note that the code was written for HttpClient 4.2.x and should work with 4.3.x and 4.4.x, but is incompatible with 4.5.x.

Watch out the last words. Axis 2 1.7.8 pom file, and the binary distribution contains the httpclient-4.5.3.jar, but doesn't work with it. So use httpclient 4.4.1 instead.

Enable logging

Before the upgrade, I suppose you already have a working axis 2 project. I recommend to enable axis 2 debug logging, to see what happens. To enable logging define a custom log4j propery file with jvm argument:

-Dlog4j.configuration=file:/c:/work/sources/debug_log4j.properties

The content of the debug_log4j.properties file is:

log4j.rootCategory=DEBUG, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %m%n 

Axis2 + Httpclient4

If you doesn't have axis2.xml, you can found it in axis2 binary package (contains all the dependencies and example configs)

Based on the release notes, you need to change the transport senders from CommonsHTTPTransportSender to HTTPClient4TransportSender.

If you look (or debug) axis2 configurator, you see, the xml must contain specific parts otherwise axis2 doesn't read it.

So my axis2.xml content after configured to use HttpClient4 (and removed unused parts, but keep essential ones):

<axisconfig name="AxisJava2.0">
    <!-- ================================================= -->
    <!-- Transport Outs -->
    <!-- ================================================= -->
    <parameter name="hotdeployment">true</parameter>
    <parameter name="hotupdate">false</parameter>
    <parameter name="enableMTOM">false</parameter>
    <parameter name="enableSwA">false</parameter>   

    <transportSender name="local"
                     class="org.apache.axis2.transport.local.LocalTransportSender"/>

    <transportSender name="http"
                     class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender">
        <parameter name="PROTOCOL">HTTP/1.1</parameter>
        <parameter name="Transfer-Encoding">chunked</parameter>

        <!-- If following is set to 'true', optional action part of the Content-Type will not be added to the SOAP 1.2 messages -->
        <!--  <parameter name="OmitSOAP12Action">true</parameter>  -->
    </transportSender>

    <transportSender name="https"
                     class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender">
        <parameter name="PROTOCOL">HTTP/1.1</parameter>
        <parameter name="Transfer-Encoding">chunked</parameter>
    </transportSender>

     <!-- ================================================= -->
    <!-- Phases  -->
    <!-- ================================================= -->
    <phaseOrder type="InFlow">
        <!--  System predefined phases       -->
        <phase name="Transport">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher">
                <order phase="Transport"/>
            </handler>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher">
                <order phase="Transport"/>
            </handler>
        </phase>
        <phase name="Addressing">
            <handler name="AddressingBasedDispatcher"
                     class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
                <order phase="Addressing"/>
            </handler>
        </phase>
        <phase name="Security"/>
        <phase name="PreDispatch"/>
        <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
            <handler name="RequestURIOperationDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
            <handler name="SOAPMessageBodyBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
            <handler name="HTTPLocationBasedDispatcher"
                     class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
            <handler name="GenericProviderDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
            <handler name="MustUnderstandValidationDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
        </phase>
        <phase name="RMPhase"/>
        <!--  System predefined phases       -->
        <!--   After Postdispatch phase module author or service author can add any phase he want      -->
        <phase name="OperationInPhase">
            <handler name="MustUnderstandChecker"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandChecker">
                <order phase="OperationInPhase"/>
            </handler>
        </phase>
        <phase name="soapmonitorPhase"/>
    </phaseOrder>
    <phaseOrder type="OutFlow">
        <!--      user can add his own phases to this area  -->
        <phase name="soapmonitorPhase"/>
        <phase name="OperationOutPhase"/>
        <!--system predefined phase-->
        <!--these phase will run irrespective of the service-->
        <phase name="RMPhase"/>
        <phase name="PolicyDetermination"/>
        <phase name="MessageOut"/>
        <phase name="Security"/>
    </phaseOrder>
    <phaseOrder type="InFaultFlow">
        <phase name="Addressing">
            <handler name="AddressingBasedDispatcher"
                     class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
                <order phase="Addressing"/>
            </handler>
        </phase>
        <phase name="Security"/>
        <phase name="PreDispatch"/>
        <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
            <handler name="RequestURIOperationDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
            <handler name="SOAPMessageBodyBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
            <handler name="HTTPLocationBasedDispatcher"
                     class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
            <handler name="GenericProviderDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
            <handler name="MustUnderstandValidationDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
        </phase>
        <phase name="RMPhase"/>
        <!--      user can add his own phases to this area  -->
        <phase name="OperationInFaultPhase"/>
        <phase name="soapmonitorPhase"/>
    </phaseOrder>
    <phaseOrder type="OutFaultFlow">
        <!--      user can add his own phases to this area  -->
        <phase name="soapmonitorPhase"/>
        <phase name="OperationOutFaultPhase"/>
        <phase name="RMPhase"/>
        <phase name="PolicyDetermination"/>
        <phase name="MessageOut"/>
        <phase name="Security"/>
    </phaseOrder>
</axisconfig> 

In the java side, you need to create a custom axis2 configuration context, to use our custom axis2.xml. Axis2 offer multiple configurator, i prefer the file based one:

final ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
    "c:\\work\\sources\\axis2conf",
    "c:\\work\\sources\\axis2conf\\axis2.xml");

You can assign the configuration context to the client stub during the constructor:

FileNet_UploadDocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");

So, if you doesn't want to use custom ssl settings, your upgrade is done.

Axis2 + Httpclient4 + SSL

After you upgraded to httpclient4, the implementation doesn't use the custom protocol handler property (HTTPConstants.CUSTOM_PROTOCOL_HANDLER) anymore.

The old implementation in org/apache/axis2/transport/http/impl/httpclient3/HTTPSenderImpl.java:524:

// one might need to set his own socket factory. Let's allow that case
// as well.
Protocol protocolHandler = (Protocol) msgCtx.getOptions().getProperty(
                HTTPConstants.CUSTOM_PROTOCOL_HANDLER);

The new implementation org/apache/axis2/transport/http/impl/httpclient4/HTTPSenderImpl.java:583:

   // TODO : one might need to set his own socket factory. We have to allow that case as well.

You need to setup ssl context in httpclient4 side. It's not a problem, because axis allow you to define httpclient for a ws call with HTTPConstants.CACHED_HTTP_CLIENT property:

options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

But if you create a httpclient4 for a standard way:

...
HttpClientBuilder builder = HttpClientBuilder.create(); 
...

and assign it to axis2 client stub, you got a ClassCastException, because all new httpclient Builder, factory, etc. methods create the "modern" implementation of httpclient, based on ClosableHttpClient. But axis2 implementation depends on deprecated AbstractHttpClient. So you need to create old version of httpclient.

The complete example:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.ssl.SSLContexts;

public class SslTest {

  public SslTest() {
    // TODO Auto-generated constructor stub
  }


  public static void main(String[] args) throws Exception {
    File keyFile = new File("c:\\work\\sources\\ConsoleApp25\\avp-pc.jks");

    final ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
    "c:\\work\\sources\\axis2conf",
    "c:\\work\\sources\\axis2conf\\axis2.xml");    


    FileNet_UploadocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");
    FileNet_UploadDocument wsMethodReq = new FileNet_UploadDocument();
    ServiceClient serviceClient = stub._getServiceClient();
    Options options = serviceClient.getOptions();

    //keystore types: https://docs.oracle.com/javase/9/docs/specs/security/standard-names.html#keystore-types
    KeyStore keyStore = KeyStore.getInstance("jks");
    InputStream in = null;
    try {
    in = new FileInputStream(keyFile);
    keyStore.load(in, "changeit".toCharArray());
    } finally {
        if (in != null) {
            in.close();
        }
    }

    //Factory instance types: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#T5
    //on IBM servers use IbmX509 instead of SunX509
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, "changeit".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(keyStore);

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    ClientConnectionManager cm =  new SingleClientConnManager(schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(cm);


    options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
    stub.fileNet_UploadDocument(wsMethodReq);

    System.out.println("done");
  }

这篇关于如何使用 httpClient4 为 Axis2 配置 SSL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆