/    Sign up×
Community /Pin to ProfileBookmark

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

to post a comment
Java

20 Comments(s)

Copy linkTweet thisAlerts:
@criterion9Sep 21.2011 — I found the following snippet:
<i>
</i>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&amp;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-post-request-ssl-https-url.html


Also see: http://www.devdaily.com/blog/post/java/simple-https-example to make sure SSL connections are working from the server in general.
Copy linkTweet thisAlerts:
@sofiauthorSep 22.2011 — 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? ?
Copy linkTweet thisAlerts:
@criterion9Sep 22.2011 — 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? ?[/QUOTE]


Are you having difficulty because the server requires a signed client certificate?

http://stackoverflow.com/questions/875467/java-client-certificates-over-https-ssl
Copy linkTweet thisAlerts:
@criterion9Sep 22.2011 — Also found: http://emo.sourceforge.net/cert-login-howto.html

Might help you to setup the client side PKI.
Copy linkTweet thisAlerts:
@sofiauthorSep 22.2011 — 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;
}
}

[/CODE]
Copy linkTweet thisAlerts:
@criterion9Sep 22.2011 — 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;
}
}

[/CODE]
[/QUOTE]

The top part of the link I posted has configuration for server side. The [B]bottom portion[/B] had to do with using PKI with [B]Client[/B] apps.
Copy linkTweet thisAlerts:
@sofiauthorSep 23.2011 — 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();
...
[/CODE]


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
Copy linkTweet thisAlerts:
@criterion9Sep 23.2011 — 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();
...
[/CODE]


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[/QUOTE]

Did you properly add the CA cert for your server cert to your JRE keystore?
Copy linkTweet thisAlerts:
@sofiauthorSep 23.2011 — 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.
Copy linkTweet thisAlerts:
@sofiauthorSep 24.2011 — 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
Copy linkTweet thisAlerts:
@sofiauthorSep 25.2011 — Thanks much,

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

Have a good day ?
Copy linkTweet thisAlerts:
@kunalkrishnaJul 26.2012 — Hi Sofi,

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

Thanks,

Kunal.
Copy linkTweet thisAlerts:
@sofiauthorJul 27.2012 — 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 [COLOR="red"]strBuffer[/COLOR]) {

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 = "[COLOR="red"]mykeycert[/COLOR].p12";

//set Keystore password
final String KEYSTOREPASS = "[COLOR="red"]yourKeyPass[/COLOR]";

//put your cacerts directly in Project Directory
TRUESTORE = "[COLOR="red"]cacerts[/COLOR]";

//set Truestore password
final String TRUESTOREPASS= "[COLOR="red"]yourTruePass[/COLOR]";

//my server URL
String httpsURL = "https://[COLOR="red"]yourserver[/COLOR]";

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 "";
}
[/CODE]



Good Luck !!
Copy linkTweet thisAlerts:
@namratasinghMay 23.2019 — Hi sofi,

I want to send a pfx certificate in java with a password that CA has given to us.
Copy linkTweet thisAlerts:
@namratasinghMay 23.2019 — Hi sofi,

what is mycerts.P12 ? is it PFX file ?
Copy linkTweet thisAlerts:
@namratasinghMay 23.2019 — public String POSTSSl(String file) {


try {
//for HttpsURLConnection we need to set this property
System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");

String KEYSTORE = "", truststore = "";


//put your keystore cert directly in Project Directory
KEYSTORE = "keystore";

//set Keystore password
final String KEYSTOREPASS = "changeit";

//put your cacerts directly in Project Directory
truststore = "cacerts";

//set Truestore password
final String TRUESTOREPASS= "changeit";

//my server URL
String httpsURL = "https://dir-staging.surescripts.net/directory/Directory6dot1/v6_1?id=12346";

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(truststore), TRUESTOREPASS.toCharArray());

//just tested if my certificate was imported in root Cacert
java.security.cert.Certificate cert = ksTrust.getCertificate("addcertificate");

//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", truststore);
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 = file.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 "";

}
}

Copy linkTweet thisAlerts:
@namratasinghMay 23.2019 — I am getting 403 forbidden error
Copy linkTweet thisAlerts:
@kristelfstMar 13.2020 — Hi,

I'm having difficulty connecting to Surecripts’ E-Prescription (https://smr-staging.surescripts.net/erx/{PortalName}/{Version}?id=

{MessageID})

I have already installed certificate (p7b file).

Does anyone here knows HTTPS Post with client certificate? or have previous experience with Surescripts Network?

I really need help.
Copy linkTweet thisAlerts:
@bafanamusicMar 18.2020 — [Url=https://bafanamusic.com] audio download [/url]

[Url=https://bafanamusic.com] bafanamusic [/url]

[Url=https://bafanamusic.com] latest mp3 download [/url]

[Url=https://bafanamusic.com] latest Ghanaian Songs [/url]

[Url=https://bafanamusic.com] justin bieber vatican mp3 [/url]

[Url=https://bafanamusic.com] latest south african songs [/url]

[Url=https://bafanamusic.com] latest hiphop songs [/url]

[Url=https://bafanamusic.com] latest naija songs [/url]

[Url=https://bafanamusic.com] mp3 album download [/url]

[Url=https://bafanamusic.com] audio download [/url]

[Url=http://beatnaija.com] Mp3 album download [/url]

[Url=http://beatnaija.com] beatnaija [/url]

[Url=http://beatnaija.com] Latest Naija Songs [/url]

[Url=http://beatnaija.com] instrumental [/url]

[Url=http://beatnaija.com] gospel [/url]

[Url=http://beatnaija.com] music [/url]

[Url=http://beatnaija.com] album [/url]

[Url=http://beatnaija.com] audio download [/url]

[Url=https://soccapro.com] 2 sure odds daily [/url]

[Url=https://soccapro.com] 3 sure odds daily [/url]

[Url=https://soccapro.com] 5 sure odds daily [/url]

[Url=https://soccapro.com] free betting tips [/url]
×

Success!

Help @sofi spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...