Java HttpsURLConnection example

Here’s a simple Java HTTPS client to demonstrate the use of HttpsURLConnection class to send a HTTP GET request yo get the https URL content and certificate detail.

P.S You may interest at this example – automate login a website with HttpsURLConnection.

HttpsClient.java

package com.mkyong.client;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.io.*;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;

public class HttpsClient{
	
   public static void main(String[] args)
   {
        new HttpsClient().testIt();
   }
	
   private void testIt(){

      String https_url = "https://www.google.com/";
      URL url;
      try {

	     url = new URL(https_url);
	     HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
			
	     //dumpl all cert info
	     print_https_cert(con);
			
	     //dump all the content
	     print_content(con);
			
      } catch (MalformedURLException e) {
	     e.printStackTrace();
      } catch (IOException e) {
	     e.printStackTrace();
      }

   }
	
   private void print_https_cert(HttpsURLConnection con){
     
    if(con!=null){
			
      try {
				
	System.out.println("Response Code : " + con.getResponseCode());
	System.out.println("Cipher Suite : " + con.getCipherSuite());
	System.out.println("\n");
				
	Certificate[] certs = con.getServerCertificates();
	for(Certificate cert : certs){
	   System.out.println("Cert Type : " + cert.getType());
	   System.out.println("Cert Hash Code : " + cert.hashCode());
	   System.out.println("Cert Public Key Algorithm : " 
                                    + cert.getPublicKey().getAlgorithm());
	   System.out.println("Cert Public Key Format : " 
                                    + cert.getPublicKey().getFormat());
	   System.out.println("\n");
	}
				
	} catch (SSLPeerUnverifiedException e) {
		e.printStackTrace();
	} catch (IOException e){
		e.printStackTrace();
	}

     }
	
   }
	
   private void print_content(HttpsURLConnection con){
	if(con!=null){
			
	try {
		
	   System.out.println("****** Content of the URL ********");			
	   BufferedReader br = 
		new BufferedReader(
			new InputStreamReader(con.getInputStream()));
				
	   String input;
				
	   while ((input = br.readLine()) != null){
	      System.out.println(input);
	   }
	   br.close();
				
	} catch (IOException e) {
	   e.printStackTrace();
	}
			
       }
		
   }
	
}

Output…


Response Code : 200
Cipher Suite : SSL_RSA_WITH_RC4_128_SHA

Cert Type : X.509
Cert Hash Code : 7810131
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509

Cert Type : X.509
Cert Hash Code : 6042770
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509

****** Content of the URL ********
<!doctype html><html><head><meta http-equiv="content-type" ......
Note
For more detail usage, please refer to this example - Send HTTP Request GET/POST In Java

References

  1. Send HTTP Request GET/POST In Java
  2. Apache HttpClient examples

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
BG
Guest
BG

Hi , I tried to run example on my RAD7(workstation) , throwing following error:

java.net.SocketException: Cannot find the specified class java.security.PrivilegedActionException: java.lang.ClassNotFoundException: com.ibm.websphere.ssl.protocol.SSLSocketFactory

at javax.net.ssl.DefaultSSLSocketFactory.createSocket(SSLSocketFactory.java:8)

at com.ibm.net.ssl.www2.protocol.https.b.afterConnect(b.java:15)

at com.ibm.net.ssl.www2.protocol.https.c.connect(c.java:3)

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:942)

at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)

at com.ibm.net.ssl.www2.protocol.https.a.getResponseCode(a.java:2)

at com.atradius.linkedIn.OAuthUtils.testIt(OAuthUtils.java:512)

at com.atradius.linkedIn.OAuthUtils.main(OAuthUtils.java:500)

Any help much appreciated!

Bala
Guest
Bala

If anyone getting certificate issue and running behind firewall where you have to go through proxy. then add these lines after.

url = new URL(https_url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty(“https.proxyHost”,proxy);
systemProperties.setProperty(“https.proxyPort”,port);

authentication if required any.

atul darne
Guest
atul darne

how if i need to download a file that is in the server directory

Manoj
Guest
Manoj

Hi,
Good tutorial, It would be great if you could provide the example with writing to the connection scenario using the OutputStream from HttpsURLConnection object.

Kamil H
Guest
Kamil H

javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair

at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1762)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1723)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1706)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1237)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1214)

at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)

at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)

at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)

at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)

at HttpsClient.print_https_cert(HttpsClient.java:45)

at HttpsClient.testIt(HttpsClient.java:26)

at HttpsClient.main(HttpsClient.java:13)

Caused by: java.lang.RuntimeException: Could not generate DH keypair

at com.sun.net.ssl.internal.ssl.DHCrypt.(DHCrypt.java:106)

at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverKeyExchange(ClientHandshaker.java:556)

at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:183)

at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)

at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)

at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:958)

Iwan Saifudin
Guest
Iwan Saifudin

Good tutorial. Thanks Mkyong.

abc
Guest
abc
i have to pass the xml a https url and get the response. but i am getting the following error at con.getResponseCode() Could any one please help me java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source) at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source) at com.xml.TestURL.print_https_cert at com.xml.TestURL.testIt at com.xml.TestURL.main java.net.SocketException: Connection reset at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)… Read more »
Abhishek Pandey
Guest
Abhishek Pandey

Please try to pass your Proxy object in the openConnection() method.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(“proxy.abc.com”, 8080));
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);

shashi
Guest
shashi

getting syttac error near type and proxy.abc.com

sham
Guest
sham

If you have an internal proxy server,
You need to include the following vm arguments
-Dhttps.proxyHost=proxy.xyz.com
-Dhttps.proxyPort=7070

abc
Guest
abc

I am getting below error could you pleease help me for the same, in
OutputStream out = connection.getOutputStream();

Exception in thread “main” java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)

BARKAT
Guest
BARKAT

Hi

i need someone help me how do i create a simple HttpsSerer for java

DNavarro
Guest
DNavarro

I need to download and print this html page from my localhost, but the error

javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown

does not allow me to do that. Could you please help me to set up what it is needed to do that?

Thank you in advance.

Regards.

Asiri Indrajith
Guest
Asiri Indrajith

This is working for me. How can I implement this for client authentication(2-way SSL)?

Anunay
Guest
Anunay
getting the below error – while trying to run the code in JDK 1.6 version. any help will be appriciated.. java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source) at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.protocol.https.HttpsClient.(Unknown Source) at sun.net.www.protocol.https.HttpsClient.New(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source) at HttpsClient.print_https_cert(HttpsClient.java:45) at HttpsClient.testIt(HttpsClient.java:26) at HttpsClient.main(HttpsClient.java:13) ****** Content of the URL ******** java.net.ConnectException: Connection refused: connect at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)… Read more »
mayank sharma
Guest
mayank sharma

i am also facing same issue.

Pravin
Guest
Pravin

Import the yahoo certificate to your JDK cacerts file and try again

Sam
Guest
Sam

Goooooooood, Thanks a lot…mkyong

jjacquet
Guest
jjacquet

Works perfectly. Thank you sir.

Lieu R G
Guest
Lieu R G

hi

thanks for the code above, this works fine for google ,yahoo , facebook etc , why its not working for our websie ,having installed ssl trial certificate. i am getting following error

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
please help me

narendar chary
Guest
narendar chary

Hi,
Here in the sample code how are we able to get the Certificates from the server eventhough we did not validated the HostName,CA which is mandatory while SSL handshake.

Thanks,
Narendar

Chirag
Guest
Chirag

Hi i have 2 question.
1) i need expire date for the certificate.(As i already try this code ((X509Certificate) certs).checkValidity(d); but i need proper date of expire.

Ques 2) Here in Certificate[] certs = con.getServerCertificates();, i am getting array of certificates i.e multiple certificate, so which one i have to check , my requirement is to get same expire date which we show in browser on firing the URL.

Pls help me out.
Thanks in Adv.
Chirag Shah.

Cor Broekhuis
Guest
Cor Broekhuis

1. cert.toString() will give you all info including expire date

2. First is the certificate you need. Second is intermediate certificate

Charith
Guest
Charith
2012-07-31 10:32:27,901 [http-8080-15] ERROR pfaddonscat – MYDOCUMENTS: :Unrecognized SSL message, plaintext connection? RequestMap:{ui=xbrowser, application=mydocuments, FATAL_ERROR_THROWABLE=java.lang.reflect.InvocationTargetException, FILEDESCRIPTION=testing, FILETITLE=test, SID=4C91AA8EB36CC2D02E0395BF234DF2D4, IID=-1, pf.mwpef.engine.uiPackage=xbrowser, pf.mwpef.engine.uiStyle=html-v3.xsl, CATEGORY=1, applicationtype=MYDOCUMENTSE, style=html, keytype=ENTER, _USER_DIVISION_NAME=, FATAL_ERROR=COMMON_MWPEF00002} Stacktrace: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection? at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:523) at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:355) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:623) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:506) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at de.pepperlfuchs.modules.mydocuments.MYDOCUMENTSEWrapper.saveCurrentDetails(MYDOCUMENTSEWrapper.java:97) at de.pepperlfuchs.mwpef.modules.aiobjects.AbstractModuleEWrapper.executeENTER(AbstractModuleEWrapper.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at de.pepperlfuchs.mwpef.modules.RequestDispatcher.execute(RequestDispatcher.java:83) at de.pepperlfuchs.mwpef.engine.action.AbstractAction.dispatchRequestToModule(AbstractAction.java:209) at de.pepperlfuchs.mwpef.engine.action.GenericAction.handleModuleDispatch(GenericAction.java:163) at de.pepperlfuchs.mwpef.engine.action.GenericAction.handleActionExecute(GenericAction.java:70) at de.pepperlfuchs.mwpef.engine.action.AbstractAction.execute(AbstractAction.java:49) at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58) at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67) at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191) at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191) at… Read more »
madhu
Guest
madhu

Thanks a lot…. mkyong
till now i dont know to download secure http pages into my local sys.

Nanna Rahi
Guest
Nanna Rahi

Has this code worked for anybody. Here it is throwing java.net.UnknownHostException

Kriss
Guest
Kriss

Hi

I`m exploring HttpsUrlConnection second week and I`ve no idea how to force it to reuse open connection.

Can you help me?

I need SNI, client certs and custom trustStore (I`m using my own CA). Regardless if I use my own CA or global one (GoDaddy), on server side via tshark I can see that connection is being close my Android app (TCP FIN packet). Even is second transaction is call right after the first one.

Regards

Giacomo
Guest
Giacomo

Perfect!

Sonu
Guest
Sonu

Above code does not work.. it gives UnknownHostException.
I want to connect to https URL with username and password. when i try to open url in browser it prompts me for Username and password and after typing credentials it displayes xml which i need to save into xml file.. this is the requirement which i need to do in java. can you tell me how to do it?

gene bidwell
Guest
gene bidwell

If this is a server proxy problem how do I get around it.
C:\MSD\source4>java HttpsClient
java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)

at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:272)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)

at HttpsClient.print_https_cert(HttpsClient.java:65)
at HttpsClient.testIt(HttpsClient.java:46)
at HttpsClient.main(HttpsClient.java:33)
****** Content of the URL ********

Darshana
Guest
Darshana

Hi,

I’m having an issue with HttpsUrlConnection. I’m writing my request to the connection outputstream but I don’t get anything in inputstream. It’s empty.

So I tried with your code by setting my URL but still i have the same issue.

Any help will be appreciated.

Thanks,
Darshana

trackback
Java HTTPS client – HttpsURLConnection example « Kata learns to code