www.webdeveloper.com
+ Reply to Thread
Results 1 to 15 of 15
  1. #1
    Join Date
    Aug 2009
    Posts
    20

    POST request to SSL/HTTPS URL Java

    Hello Everyone,

    I have done Posting request to https URL(using ssl)in c sharp very easily.
    Now I am trying to do the same in Java. I already installed JSSE successfully. Next thing i have to do is to set certificate (i already have valid certificate).

    Please, can anyone tell me how to set my certificate?

    Thanks much for attention

  2. #2
    Join Date
    Jan 2009
    Posts
    3,341
    I found the following snippet:
    Code:
    mport java.io.*;
    import java.net.*;
    import java.security.cert.*;
    
    import javax.net.ssl.*;
    
    public class HttpsPost {
    public static void main(String[] args) throws Exception {
    SSLContext sslctx = SSLContext.getInstance("SSL");
    sslctx.init(null, new X509TrustManager[] { new MyTrustManager()
    }, null);
    
    HttpsURLConnection.setDefaultSSLSocketFactory(sslc tx.getSocketFactory());
    URL url = new URL("https://www.xxxx.dk/htbin/tell2");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    PrintStream ps = new PrintStream(con.getOutputStream());
    ps.println("f1=abc&f2=xyz");
    ps.close();
    con.connect();
    if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
    BufferedReader br = new BufferedReader(new
    InputStreamReader(con.getInputStream()));
    String line;
    while((line = br.readLine()) != null) {
    System.out.println(line);
    }
    br.close();
    }
    con.disconnect();
    }
    }
    
    class MyTrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String
    authType) {
    }
    
    public void checkServerTrusted(X509Certificate[] chain, String
    authType) {
    }
    
    public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
    }
    }
    Here: http://www.techtalkz.com/java/118351...https-url.html


    Also see: http://www.devdaily.com/blog/post/ja...-https-example to make sure SSL connections are working from the server in general.

  3. #3
    Join Date
    Aug 2009
    Posts
    20

    Question I need to set my custom certificate

    Thanks a lot for replying to me

    But thing is that i want to indicate in code my own certificate. I did it in c# as follows:
    ...
    X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
    ...
    //Add Client Certificate
    WebReq.ClientCertificates.Add(certificate);
    ...

    It is not the whole code, just wanted to show how I add my custom certificate (strCertFile), which i have in my project. I want to do same in Java, and could not find out how to do that?

  4. #4
    Join Date
    Jan 2009
    Posts
    3,341
    Quote Originally Posted by sofi View Post
    Thanks a lot for replying to me

    But thing is that i want to indicate in code my own certificate. I did it in c# as follows:
    ...
    X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
    ...
    //Add Client Certificate
    WebReq.ClientCertificates.Add(certificate);
    ...

    It is not the whole code, just wanted to show how I add my custom certificate (strCertFile), which i have in my project. I want to do same in Java, and could not find out how to do that?
    Are you having difficulty because the server requires a signed client certificate?

    http://stackoverflow.com/questions/8...over-https-ssl

  5. #5
    Join Date
    Jan 2009
    Posts
    3,341
    Also found: http://emo.sourceforge.net/cert-login-howto.html

    Might help you to setup the client side PKI.

  6. #6
    Join Date
    Aug 2009
    Posts
    20

    Problem in Console App

    Thanks again,

    But I am writing console application not the web application, therefore i dont need to Set up Tomcat to Require Client Authentication. Can you have a look to my code in C#? i just want the same in java

    Code:
    //Post Request with custom Certificate
            private string PostSSL(string strPage, string strBuffer)
            {
                try
                {
                    //Our postvars
                    byte[] buffer = Encoding.UTF8.GetBytes(strBuffer);
    
                    //Initialisation
                    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(strPage);
                    //Our method is post, otherwise the buffer (postvars) would be useless
                    WebReq.Method = "POST";
                    WebReq.KeepAlive = false;
    
                    //Import Client Certificate
                    string strCertFile = Application.StartupPath +
                        CConsts.csFolder_Certificate + global::E_Terminal.Properties.appl.Default.ClientCertFile;
                    string strCertPwd = global::E_Terminal.Properties.appl.Default.ClientCertPass;
                    X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
    
                    //We use form contentType, for the postvars.
                    WebReq.ContentType = "application/x-www-form-urlencoded";
                    //The length of the buffer (postvars) is used as contentlength.
                    WebReq.ContentLength = buffer.Length;
    
                    //Add Client Certificate
                    WebReq.ClientCertificates.Add(certificate);
    
                    WebReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
    
                    //We open a stream for writing the postvars
                    Stream PostData = WebReq.GetRequestStream();
    
                    //Now we write, and afterwards, we close. Closing is always important!
                    PostData.Write(buffer, 0, buffer.Length);
                    PostData.Close();
                    //Get the response handle, we have no true response yet!
                    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
    
                    //Now, we read the response (the string), and output it.
                    Stream Answer = WebResp.GetResponseStream();
                    StreamReader _Answer = new StreamReader(Answer);
                    //Console.WriteLine(_Answer.ReadToEnd());
                    return _Answer.ReadToEnd();
                }
                catch (Exception ex)
                {
                    CUtils.ErrorHandler(ex);
                    return String.Empty;
                }
            }

  7. #7
    Join Date
    Jan 2009
    Posts
    3,341
    Quote Originally Posted by sofi View Post
    Thanks again,

    But I am writing console application not the web application, therefore i dont need to Set up Tomcat to Require Client Authentication. Can you have a look to my code in C#? i just want the same in java

    Code:
    //Post Request with custom Certificate
            private string PostSSL(string strPage, string strBuffer)
            {
                try
                {
                    //Our postvars
                    byte[] buffer = Encoding.UTF8.GetBytes(strBuffer);
    
                    //Initialisation
                    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(strPage);
                    //Our method is post, otherwise the buffer (postvars) would be useless
                    WebReq.Method = "POST";
                    WebReq.KeepAlive = false;
    
                    //Import Client Certificate
                    string strCertFile = Application.StartupPath +
                        CConsts.csFolder_Certificate + global::E_Terminal.Properties.appl.Default.ClientCertFile;
                    string strCertPwd = global::E_Terminal.Properties.appl.Default.ClientCertPass;
                    X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
    
                    //We use form contentType, for the postvars.
                    WebReq.ContentType = "application/x-www-form-urlencoded";
                    //The length of the buffer (postvars) is used as contentlength.
                    WebReq.ContentLength = buffer.Length;
    
                    //Add Client Certificate
                    WebReq.ClientCertificates.Add(certificate);
    
                    WebReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
    
                    //We open a stream for writing the postvars
                    Stream PostData = WebReq.GetRequestStream();
    
                    //Now we write, and afterwards, we close. Closing is always important!
                    PostData.Write(buffer, 0, buffer.Length);
                    PostData.Close();
                    //Get the response handle, we have no true response yet!
                    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
    
                    //Now, we read the response (the string), and output it.
                    Stream Answer = WebResp.GetResponseStream();
                    StreamReader _Answer = new StreamReader(Answer);
                    //Console.WriteLine(_Answer.ReadToEnd());
                    return _Answer.ReadToEnd();
                }
                catch (Exception ex)
                {
                    CUtils.ErrorHandler(ex);
                    return String.Empty;
                }
            }
    The top part of the link I posted has configuration for server side. The bottom portion had to do with using PKI with Client apps.

  8. #8
    Join Date
    Aug 2009
    Posts
    20

    Question Still Problem

    Thanks again, i followed all steps, then even i used Portecle- which allowed me to install trusted certificate. And all went good, but code still give me error:

    Code:
                System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
                System.setProperty("javax.net.ssl.trustStoreType", "jks");
                System.setProperty("javax.net.ssl.keyStore", "C:\\Program Files\\Java\\jdk1.6.0_18\\jre\\bin\\5000049.p12");
                System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.6.0_18\\jre\\lib\\security\\cacerts");
                System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
                System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    
                String httpsURL = "myurl";
    
                URL url = new URL(httpsURL);
    
                SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    
                URLConnection conn = url.openConnection();
                conn.getInputStream();
                        ...
    Then it still gives the 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

  9. #9
    Join Date
    Jan 2009
    Posts
    3,341
    Quote Originally Posted by sofi View Post
    Thanks again, i followed all steps, then even i used Portecle- which allowed me to install trusted certificate. And all went good, but code still give me error:

    Code:
                System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
                System.setProperty("javax.net.ssl.trustStoreType", "jks");
                System.setProperty("javax.net.ssl.keyStore", "C:\\Program Files\\Java\\jdk1.6.0_18\\jre\\bin\\5000049.p12");
                System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.6.0_18\\jre\\lib\\security\\cacerts");
                System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
                System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    
                String httpsURL = "myurl";
    
                URL url = new URL(httpsURL);
    
                SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    
                URLConnection conn = url.openConnection();
                conn.getInputStream();
                        ...
    Then it still gives the 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
    Did you properly add the CA cert for your server cert to your JRE keystore?

  10. #10
    Join Date
    Aug 2009
    Posts
    20
    By using Portecle I imported my server's Ca-certificate to java home Cacerts.
    And even i can see that my certificates has been added to cacerts.

    I even attached file showing that my cert has been added.

  11. #11
    Join Date
    Aug 2009
    Posts
    20

    Question still cant solve

    I am really confused with Java ssl connection.

    I read many documentation it seems that i configured everything but i am getting the same error.

    Please can you help?

    Thanks

  12. #12
    Join Date
    Jan 2009
    Posts
    3,341

  13. #13
    Join Date
    Aug 2009
    Posts
    20

    resolved

    Thanks much,

    Yesterday I read much about JSSE and keytool and resolved the problem.

    Have a good day

  14. #14
    Join Date
    Jul 2012
    Posts
    1
    Hi Sofi,

    I am facing the same issue. Can you please help me out with a solution guide.

    Thanks,
    Kunal.

  15. #15
    Join Date
    Aug 2009
    Posts
    20

    Solution for SSL connection in Java

    Hello Kunal,

    I will give you exact code, that works fine - which i did by following JSSE documentation step by step :

    Code:
    //you have to import following:
    import java.io.*;
    import java.net.*;
    import java.security.Security.*;
    import com.sun.net.ssl.*;
    import java.security.KeyStore;
    
     . . . 
    
    //firstly put ur certs directly in Project Directory
    
    //then you just have to change Red strings to your data
    
     public static String PostSSL(String strBuffer) {
    
            try {
                //for HttpsURLConnection we need to set this property
                System.setProperty("java.protocol.handler.pkgs",
                        "com.sun.net.ssl.internal.www.protocol");
    
                String KEYSTORE = "", TRUESTORE = "";
              
    
               //put your keystore cert directly in Project Directory
               KEYSTORE = "mykeycert.p12";
    
                //set Keystore password
                final String KEYSTOREPASS = "yourKeyPass";
             
              //put your cacerts directly in Project Directory
                TRUESTORE = "cacerts";
    
               //set Truestore password
                final String TRUESTOREPASS= "yourTruePass";
    
                //my server URL
                String httpsURL = "https://yourserver";
    
                URL url = new URL(httpsURL);
    
                KeyStore ks = KeyStore.getInstance("pkcs12");
                ks.load(new FileInputStream(KEYSTORE), KEYSTOREPASS.toCharArray());
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, KEYSTOREPASS.toCharArray());
    
                SSLContext sslctx2 = SSLContext.getInstance("SSLv3");
                sslctx2.init(kmf.getKeyManagers(), null, null);
    
                KeyStore ksTrust = KeyStore.getInstance("JKS");
                ksTrust.load(new FileInputStream(TRUESTORE), TRUESTOREPASS.toCharArray());
    
                //just tested if my certificate was imported in root Cacert
                java.security.cert.Certificate cert = ksTrust.getCertificate("myCert");
    
                //TrustManager's decide whether to allow connections.
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(ksTrust);
    
                System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
                System.setProperty("javax.net.ssl.trustStoreType", "jks");
                System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
                System.setProperty("javax.net.ssl.trustStore", TRUESTORE);
                System.setProperty("javax.net.debug", "ssl");
                System.setProperty("javax.net.ssl.keyStorePassword", KEYSTOREPASS);
                System.setProperty("javax.net.ssl.trustStorePassword", TRUESTOREPASS);
    
    
                sslctx2.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    
                byte[] buffer = strBuffer.getBytes("UTF-8");
                //******
                HttpsURLConnection.setDefaultSSLSocketFactory(sslctx2.getSocketFactory());
    
                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput(true);
                PrintStream ps = new PrintStream(con.getOutputStream());
                ps.write(buffer, 0, buffer.length);
                ps.close();
                con.connect();
    
                //get Response after SSL connection
                String line = "";
                String line2 = "";
    
                int myRes = con.getResponseCode();
                if (myRes == HttpsURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    line = br.readLine();
                    line2 = line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
    
                    br.close();
                }
                con.disconnect();
    
                return line2;
    
            } catch (Exception e) {
                return "";
            }

    Good Luck !!

Thread Information

Users Browsing this Thread

There are currently 2 users browsing this thread. (0 members and 2 guests)

     

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center



Recent Articles