How to use custom socketfactory in Apache HttpComponents

I am trying to use a custom SocketFactory in the httpclient library from the Apache project HTTPComponents. So far no luck. I expected that I could just set the factory socket for the HttpClient instance, but this is obviously not so simple.

The documentation for HttpComponents at http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html mentions socket factories, but does not say how to use them.

Does anyone know how to do this?

+4
source share
2 answers

We use our own factory socket to allow HttpClient connections to connect to HTTPS URLs with untrusted certificates.

Here's how we did it:

  • We adapted the implementation of the classes "EasySSLProtocolSocketFactory" and "EasyX509TrustManager" from the reference directory of examples referenced by Oleg.

  • In our HttpClient startup code, we do the following to enable the new factory socket:

    HttpClient httpClient = new HttpClient(); Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", easyhttps); 

So that anytime we request the https: // URL, this factory socket is used.

+2
source

Oleg's answer, of course, is correct, I just wanted to post the information right here, in case the link goes wrong. In the code that HttpClient creates, I use this code so that it can use my factory socket:

  CustomSocketFactory socketFactory = new CustomSocketFactory(); Scheme scheme = new Scheme("http", 80, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); 

CustomSocketFactory is my own factory socket, and I want to use it for regular HTTP traffic, so I use "http" and 80 as parameters.

My CustomSchemeSocketFactory looks something like this:

 public class CustomSchemeSocketFactory implements SchemeSocketFactory { @Override public Socket connectSocket( Socket socket, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (localAddress != null) { socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); socket.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { socket.setSoTimeout(soTimeout); socket.connect(remoteAddress, connTimeout ); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } return socket; } @Override public Socket createSocket( HttpParams params ) throws IOException { // create my own socket and return it } @Override public boolean isSecure( Socket socket ) throws IllegalArgumentException { return false; } } 
+2
source

Source: https://habr.com/ru/post/1382494/


All Articles