New tool class for access to self-signed HTTPS websites based on httpclient 4.3

Source: Internet
Author: User
Tags ssl connection

The source of this article: http://blog.csdn.net/chaijunkun/article/details/40145685, reprint please specify. Because I do not regularly collate the relevant blog post, the corresponding content will be made intact. It is therefore highly recommended to view this article in the original source.


The location of httpclient in today's Java applications is becoming increasingly important. From the evolution of the project , it is easy to see that it has been stripped from Apache-commons's numerous sub-projects and has become a top-notch project now. It is visible in its component. However, as the project is upgraded and the architecture is adjusted. Many of the classes and methods that were used frequently have been @deprecated annotated as a programmer with code cleanliness. We also need to upgrade the tool class to make the code more uncluttered.

In addition, the interface to the HTTPS protocol needs to be visited in the project. and the corresponding server did not buy a commercial CA issued by the official letter of the certificate, Just do a self-signed (Lenovo 12306 site ticketing when the warning message). By default, httpclient access throws an exception, and the workaround is given in this article.


A number of constructor design patterns were introduced in the HttpClient 4.x version number. Very many configurations are not recommended for direct new. And the relevant API has also been modified, such as connection parameters, once the direct new out of the Httpconnectionparams object through the Set method of setting properties, now has a constructor. Can be constructed in such a way as the following:

Connectionconfig.custom (). Setcharset (Charsets.tocharset (defaultencoding)). Build ();

Socketconfig.custom (). Setsotimeout (100000). build ();

The basic situation is this, and next talk about how to use the new httpclient to access the self-signed HTTPS interface.


See CSDN Blogger noodies Code, discover the implementation the key to visiting self-signed HTTPS is to create a Sslcontext object of your own definition. The object needs to have a container that can store the trust key. There is also a policy that infers whether the current connection is trusted, and cancels the validation of all hostnames in the SSL connection factory. His code will be posted at the end of this article, and the code below is for the new httpclient.


Start by building a strategy that trusts no matter what key. The code is very easy, and does not consider the certificate chain and the type of authorization, are considered to be trusted:

Class Anytruststrategy implements truststrategy{@Overridepublic Boolean istrusted (x509certificate[] chain, String AuthType) throws Certificateexception {return true;}}

HttpClient can handle both the regular HTTP protocol and HTTPS, the root of which is to register different connection creation factories in the connection manager. When visiting the schema of the URL for HTTP, call clear text to connect to the nested node factory to establish the connection. When visiting the URL schema for HTTPS, call the SSL connection socket factory to establish the connection. We do not make changes to the HTTP connection. Make your own definition only for HTTPS connections that use SSL:

RegistryBuilder <ConnectionSocketFactory> Registrybuilder = Registrybuilder.<connectionsocketfactory>create (); Connectionsocketfactory plainsf = new Plainconnectionsocketfactory () registrybuilder.register ("http", PlainSF);// Specify the Trust key store object and the connection socket factory try {KeyStore Truststore = keystore.getinstance (Keystore.getdefaulttype ()); Sslcontext Sslcontext = Sslcontexts.custom (). USETLS (). Loadtrustmaterial (Truststore, New Anytruststrategy ()). Build () ; Layeredconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, Sslconnectionsocketfactory.allow_ All_hostname_verifier); Registrybuilder.register ("https", SSLSF);} catch (Keystoreexception e) {throw new RuntimeException (e);} catch (Keymanagementexception e) {throw new runtimeexception (e);} catch (NoSuchAlgorithmException e) {throw new RuntimeException (e);} registry<connectionsocketfactory> Registry = Registrybuilder.build (); 
can be seen in the code above. First, a key storage container is established, which then lets Sslcontext turn on TLS, and loads the key storage container and the policy that trusts the host, regardless of its hosts, into that context. When you construct an SSL connection factory, you pass in both your own defined context and the consent to verify whatever host name is passed. Finally, a custom SSL connection factory is registered to the HTTPS protocol.

The preparation is complete, and we want to get the HttpClient object:

Set Connection Manager Poolinghttpclientconnectionmanager Connmanager = new Poolinghttpclientconnectionmanager (registry); Connmanager.setdefaultconnectionconfig (Connconfig); Connmanager.setdefaultsocketconfig (socketConfig);// Build the client httpclient client= httpclientbuilder.create (). Setconnectionmanager (Connmanager). build ();
to make our httpclient capable of multithreading, the Connection Manager chooses the Poolinghttpclientconnectionmanager to pass the Protocol registration information to the Connection Manager, Finally, we use the constructor mode to create the httpclient we need. There is no difference between HTTP and HTTPS for the subsequent Get/post request initiation method.

To verify that our code was successful, we were able to do the JUnit unit test:

@Testpublic void Dotest () throws Clientprotocolexception, urisyntaxexception, ioexception{httputil util = Httputil.getinstance (); InputStream in = Util.doget ("Https://kyfw.12306.cn/otn/leftTicket/init"); String RetVal = Httputil.readstream (in, httputil.defaultencoding); System.out.println (RetVal);}

HTML code to see more than 12,306 ticket queries on the console after running

In order to facilitate everyone to use, I will encapsulate the code uploaded to the CSDN resource sharing, welcome to download.

: http://download.csdn.net/detail/chaijunkun/8046331

Finally thanked csdn Bo main Noodies's Code provides the idea: http://blog.csdn.net/noodies/article/details/17240805

Some of the code in this article is part of section 2.7 of the HttpClient 4.3.5 Official document about connection socket factories

New tool class for access to self-signed HTTPS websites based on httpclient 4.3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.