Java HTTPS client – HttpsURLConnection example
Here’s a simple Java HTTPS client to demonstrate the use of HttpsURLConnection class to print a https URL content and certificate detail.
Access https URL : https://www.google.com/
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" ......
Tags : http client https java ssl

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.
This is working for me. How can I implement this for client authentication(2-way SSL)?
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)
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)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at HttpsClient.print_content(HttpsClient.java:76)
at HttpsClient.testIt(HttpsClient.java:29)
at HttpsClient.main(HttpsClient.java:13)
Caused by: 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)
… 1 more
Goooooooood, Thanks a lot…mkyong
Works perfectly. Thank you sir.
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
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
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.
1. cert.toString() will give you all info including expire date
2. First is the certificate you need. Second is intermediate certificate
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 org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at de.pepperlfuchs.mwpef.engine.action.CharsetFilter.doFilter(CharsetFilter.java:31)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
at java.lang.Thread.run(Thread.java:619)
Can anyone help out to get out of this. i’m using Httpclient and post method to connect to Https.
Thanks a lot…. mkyong
till now i dont know to download secure http pages into my local sys.
Has this code worked for anybody. Here it is throwing java.net.UnknownHostException
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
Perfect!
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?
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 ********
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
send me your code via email
Caused by: javax.net.ssl.SSLException: Inbound closed before receiving peer’s close_notify: possible truncation attack?
how if i need to download a file that is in the server directory