Java - Read data from URL

Sample code snippet to read data from an HTTP(S) url.
      
      public static void main(String[] args) throws Exception{

          URL url = new URL("https://www.google.com");
          URLConnection con = url.openConnection();

          BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
          String line;
          while ((line = br.readLine()) != null)
          {
              System.out.println(line);
          }
          br.close();
      }

If you are using https url, if you get the following error

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It means that the certificate is not available. You may have to import the certificate to your JRE.
Follow the below steps:


  1. Open the url in the browser (IE/Firefox). 
  2. Export the certificate to a file. For example: to c:/youtills.crt
  3. Open command prompt navigate to the JRE folder and run the following command.
  4. .../jre> keytool -import -alias myprivateroot -keystore lib\security\cacerts -file c:\youtills.crt

No comments:

Post a Comment