How to force Commons HTTPClient 3.1 to use TLS 1.2 only for HTTPS?

前端 未结 3 1090
独厮守ぢ
独厮守ぢ 2020-12-03 01:38

I wish to force Apache Commons HTTP-Client (version 3.1) to use TLS 1.2 as the only pro

3条回答
  •  旧时难觅i
    2020-12-03 01:50

    Too bad nobody answered; I was able to do it, first you write a CustomHttpSocketFactory, then you do:

    String scheme = "https";
    Protocol baseHttps = Protocol.getProtocol(scheme);
    int defaultPort = baseHttps.getDefaultPort();
    
    ProtocolSocketFactory baseFactory = baseHttps.getSocketFactory();
    ProtocolSocketFactory customFactory = new CustomHttpsSocketFactory(baseFactory);
    
    Protocol customHttps = new Protocol(scheme, customFactory, defaultPort);
    Protocol.registerProtocol(scheme, customHttps); 
    

    A sample custom socket factory code is found here, but instead I did:

    public class CustomHttpsSocketFactory implements SecureProtocolSocketFactory
    {
    
       private final SecureProtocolSocketFactory base;
    
       public CustomHttpsSocketFactory(ProtocolSocketFactory base)
       {
          if(base == null || !(base instanceof SecureProtocolSocketFactory)) throw new IllegalArgumentException();
          this.base = (SecureProtocolSocketFactory) base;
       }
    
       private Socket acceptOnlyTLS12(Socket socket)
       {
          if(!(socket instanceof SSLSocket)) return socket;
          SSLSocket sslSocket = (SSLSocket) socket;
          sslSocket.setEnabledProtocols(new String[]{"TLSv1.2" });
          return sslSocket;
       }
    
       @Override
       public Socket createSocket(String host, int port) throws IOException
       {
          return acceptOnlyTLS12(base.createSocket(host, port));
       }
       @Override
       public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException
       {
          return acceptOnlyTLS12(base.createSocket(host, port, localAddress, localPort));
       }
       @Override
       public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException
       {
          return acceptOnlyTLS12(base.createSocket(host, port, localAddress, localPort, params));
       }
       @Override
       public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException
       {
          return acceptOnlyTLS12(base.createSocket(socket, host, port, autoClose));
       }
    
    }
    

提交回复
热议问题