HttpClient exception when sending data to HTTPS to establish an SSL connection

Source: Internet
Author: User
Tags ssl connection
The exception information is as follows:

Javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX Path Building failed: Sun.security.provider.certpath.SunCertPathBuilderException:unable to find valid certification path to requested target

Cause: The server's certificate is not trusted. This is generally the result.

When you use the Keytool tool to create a certificate and then start with Tomcat, the certificate is not trusted when the browser opens the Web site. Of course, when using httpclient to send data to the server-side HTTPS, HttpClient also detects whether the server's certificate is trusted and throws the above exception without being trusted.

There are two workarounds, one of which is to make the certificate trusted by the client. The other is to not detect if the server certificate is trustworthy when sending data using HttpClient.

The first approach is to make the certificate trusted.

Look for a regular CA to issue a certificate, or you can issue a certificate yourself (only on that one client computer). Looking for a regular CA to issue the certificate will not say, I issued a certificate, see my other articles.

I found that when my signed certificate was ready, when I opened the server-side address from the client, I stopped prompting the above error, but I still couldn't send the data. What is the reason? Because that certificate is trusted on the client operating system, but not trusted in Java KeyStore, import the server certificate into the KeyStore library

Import Method:

Open a command-line window and go to the <java-home>\lib\security\ directory and run the following command:

Keytool-import-noprompt-keystore cacerts-storepass Changeit-alias yourentry1-file your.cer

The last one is the certificate exported by the server, others can be defaulted.

Note that if the client computer is loaded with many Java versions, to make sure that the Java version of the certificate you imported is the one that you use for Tomcat, general Tomcat uses the Java version that the environment variable points to.

If you are creating a Tomcat server in Eclipse, you will be asked to select the default JRE or Java when you create it, so you must choose the path to the Java that you just imported, or the certificate library you imported is not working.

The second approach is to not detect if the server certificate is trustworthy when using httpclient

Extending the HttpClient class implementation to automatically accept certificates

Because this method automatically receives all certificates, there are some security issues, so consider your system's security needs carefully before using this method. The specific steps are as follows:

• Provide a custom socket factory (test). Mysecureprotocolsocketfactory). This custom class must implement the interface Org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory, invoking the custom X509trustmanager in the class that implements the interface (Test. Myx509trustmanager), these two classes can be obtained in the attachments accompanying this article

• Create an instance of Org.apache.commons.httpclient.protocol.Protocol, specifying the protocol name and the default port number

Protocol Myhttps = new Protocol ("https", new Mysecureprotocolsocketfactory (), 443);

• Register the HTTPS protocol object you just created

Protocol.registerprotocol ("https", Myhttps);

• Then open the target address of HTTPS as normal programming, with the following code:

Mysecureprotocolsocketfactory.java

Import java.io.IOException;      Import java.net.InetAddress;      Import java.net.InetSocketAddress;      Import Java.net.Socket;      Import java.net.SocketAddress;      Import java.net.UnknownHostException;      Import java.security.KeyManagementException;      Import java.security.NoSuchAlgorithmException;      Import java.security.cert.CertificateException;            Import Java.security.cert.X509Certificate;      Import Javax.net.SocketFactory;      Import Javax.net.ssl.SSLContext;      Import Javax.net.ssl.TrustManager;            Import Javax.net.ssl.X509TrustManager;      Import org.apache.commons.httpclient.ConnectTimeoutException;      Import Org.apache.commons.httpclient.params.HttpConnectionParams;            Import Org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;  public class Mysecureprotocolsocketfactory implements Secureprotocolsocketfactory {private Sslcontext Sslcontext                    = NULL; Private Sslcontext Createsslcontext () {Sslcontext sslcontext=null;                  try {sslcontext = sslcontext.getinstance ("SSL");              Sslcontext.init (NULL, New Trustmanager[]{new Trustanytrustmanager ()}, New Java.security.SecureRandom ());              } catch (NoSuchAlgorithmException e) {e.printstacktrace ();              } catch (Keymanagementexception e) {e.printstacktrace ();          } return sslcontext; } private Sslcontext Getsslcontext () {if (This.sslcontext = = null) {thi              S.sslcontext = Createsslcontext ();          } return this.sslcontext;                  } public socket Createsocket (socket socket, String host, int port, Boolean autoClose)                      Throws IOException, Unknownhostexception {return Getsslcontext (). Getsocketfactory (). Createsocket (             Socket, host,         Port, AutoClose); } public Socket Createsocket (String host, int port) throws IOException, Unknownhostexcepti                      On {return Getsslcontext (). Getsocketfactory (). Createsocket (Host,          Port);                  } public Socket Createsocket (String host, int port, inetaddress clienthost, int clientport) Throws IOException, Unknownhostexception {return Getsslcontext (). Getsocketfactory (). Createso          Cket (host, Port, ClientHost, ClientPort); } public Socket Createsocket (String host, int port, inetaddress localaddress, int localpor              T, Httpconnectionparams params) throws IOException, Unknownhostexception, connecttimeoutexception { if (params = = null) {throw new IllegalArgumentException ("Parameters May is not nulL ");              } int timeout = Params.getconnectiontimeout ();              Socketfactory socketfactory = Getsslcontext (). Getsocketfactory ();              if (timeout = = 0) {return Socketfactory.createsocket (host, Port, localaddress, LocalPort);                  } else {Socket socket = Socketfactory.createsocket ();                  SocketAddress localaddr = new Inetsocketaddress (localaddress, LocalPort);                  SocketAddress remoteaddr = new Inetsocketaddress (host, Port);                  Socket.bind (LOCALADDR);                  Socket.connect (remoteaddr, timeout);              return socket;                           }}//Custom private classes private static class Trustanytrustmanager implements X509trustmanager { public void checkclienttrusted (x509certificate[] chain, String authtype) throws Certificateexcep tion {} public void checkservertrusted (x509cerTificate[] chain, String authtype) throws certificateexception {} public X509certifica              Te[] Getacceptedissuers () {return new x509certificate[]{}; }          }                      }
  • Related Article

    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.