How to connect to an HTTPS page in java using HttpsURLConnection

The folllowing code will connect to a https page (using SSL), get the response code and content.

 

If you have timeout or networking issues, check if you don’t have to modify the firewall configuration or install a SSL certificate on your JVM.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class SampleHttpsClient {
 
 public static void main(String[] args) {
  
  String host = "https://www.google.com";
  try {
   
   URL url = new URL(host);
   HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
   
   // get response code, 200 = Success
   int responseCode = httpsURLConnection.getResponseCode();
   System.out.println(responseCode);
   
   // if response == 200, display the content
   if(responseCode==200){
    System.out.println(httpsURLConnection.getContent().toString());
    BufferedReader br = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
    String line=null;
    while((line = br.readLine())!= null){
     System.out.println(line);
    }
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  } 
  
 }
 
}

 

You like this content ? Share it with you entourage !