$show=/label

Https Exception Java How To Fix suncertpathbuilderexception or SSLHandshakeException | Fix certificate problem in HTTPS

SHARE:

Different ways to fix the certificate issues such as SSLHandshakeException, SunCertPathBuilderException. Solution certificate problem in HTTPS. Https Exception Java How To Fix suncertpathbuilderexception.

In this tutorial, How to fix problems in Java on "HTTPS connection with SSL certificate Error".

Introduction:

HTTPS protocol is supported since JDK1.4 (AFAIK), you have nothing special to do.

As a java developer, if you have not been stung by the below-mentioned exception while running a Java application developed by you on your machine that hits an SSL server (https), then be prepared to get a nasty experience at some point of your coding journey.
How To Fix suncertpathbuilderexception SSLHandshakeException


Use case or Problematic Program:

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

public class ConnectHttps {
  public static void main(String[] args) throws Exception {
    URL url = new URL("https://amazon.com");
    URLConnection con = url.openConnection();
    Reader reader = new InputStreamReader(con.getInputStream());
    while (true) {
      int ch = reader.read();
      if (ch==-1) {
        break;
      }
      System.out.print((char)ch);
    }
  }
}

Output:

However, you can have a problem if the server certificate is self-signed by a testing certification authority (CA) which is not in trusted CAs of Java on the client side. An exception like

Exception in thread "main" 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


The above exception(SunCertPathBuilderException) is thrown. This is a common situation with a development server.

Solution 1:

The fix is to add the self signed certificate to trusted CAs on the client side. You do that by updating the CACERT file in the your JRE_HOME/lib directory.

Check this tutorial : http://www.java-samples.com/showtutorial.php?tutorialid=210

Solution 2:

you can override the check and accept an untrusted certificate (with the risk coming with it!).


import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

public class ConnectHttps {
  public static void main(String[] args) throws Exception {
    /*
     *  fix for
     *    Exception in thread "main" 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
     */
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

       }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
          return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
     * end of the fix
     */

    URL url = new URL("https://amazon.com");
    URLConnection con = url.openConnection();
    Reader reader = new InputStreamReader(con.getInputStream());
    while (true) {
      int ch = reader.read();
      if (ch==-1) {
        break;
      }
      System.out.print((char)ch);
    }
  }
}

Conclusion:

In this post, we saw why HTTPS exceptions will come while invoking secure URL's and possible solutions to fix suncertpathbuilderexception and SSLHandshakeException.

Original article

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Https Exception Java How To Fix suncertpathbuilderexception or SSLHandshakeException | Fix certificate problem in HTTPS
Https Exception Java How To Fix suncertpathbuilderexception or SSLHandshakeException | Fix certificate problem in HTTPS
Different ways to fix the certificate issues such as SSLHandshakeException, SunCertPathBuilderException. Solution certificate problem in HTTPS. Https Exception Java How To Fix suncertpathbuilderexception.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHufUWH71GX69jJy1kCFcXW9i_6PDrDpCP2k8lXJZtzJdIsKuUiW-Ug3LS8Q0wD5XJSbbOQXtjV4BRXXRn0FzI4rJP1KoowkAKHSucCd5agaBwpA-G04XI1HNQv96z-ExyUysNtI_DLaM/s400/How+To+Fix+suncertpathbuilderexception+SSLHandshakeException.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHufUWH71GX69jJy1kCFcXW9i_6PDrDpCP2k8lXJZtzJdIsKuUiW-Ug3LS8Q0wD5XJSbbOQXtjV4BRXXRn0FzI4rJP1KoowkAKHSucCd5agaBwpA-G04XI1HNQv96z-ExyUysNtI_DLaM/s72-c/How+To+Fix+suncertpathbuilderexception+SSLHandshakeException.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/04/java-fix-certificate-problem-in-HTTPS-suncertpathbuilderexception.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/04/java-fix-certificate-problem-in-HTTPS-suncertpathbuilderexception.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content