POST request to SSL/HTTPS URL

D

Dundonald

Has anyone got a sample code or utility that will allow a POST request
to be created to a SSL/HTTPS url?

I've spent a few hours googling and got solutions for HTTP and those
that I have found for HTTPs haven't worked.
 
D

Dundonald

Has anyone got a sample code or utility that will allow a POST request
to be created to a SSL/HTTPS url?

I've spent a few hours googling and got solutions for HTTP and those
that I have found for HTTPs haven't worked.

Sorry I failed to include the code that I have got working for HTTP,
see below, but please if anyone knows how I can amend this to connect
to a HTTPS link I'd appreciate some pointers. Thanks. Also, you'll
see below that the response back is output to System.out - how can
this HTML response text be sent back to the client's browser?


String content =
"action=&success=member_secure_home.jsp&error=error.jsp&login_id=username&password=somepassword";


URL url = new URL("http://localhost:9080/LoginServlet");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false); // you may not ask the user
connection.setDoOutput(true); // we want to send things
connection.setDoInput(true); //Only if you expect to read a
response...
connection.setUseCaches(false); //Highly recommended...
connection.setRequestProperty( "Content-type", "application/x-www-form-
urlencoded" );
connection.setRequestProperty( "Content-length",
Integer.toString(content.length()));

// get the output stream to POST our form data
OutputStream rawOutStream = connection.getOutputStream();
PrintWriter pw = new PrintWriter(rawOutStream);

pw.print(content); // here we "send" our body!
pw.flush();
pw.close();



// get the input stream for reading the reply
// IMPORTANT! Your body will not get transmitted if you get the
// InputStream before completely writing out your output first!
InputStream rawInStream = connection.getInputStream();

// get response
BufferedReader rdr = new BufferedReader(new
InputStreamReader(rawInStream));
String line;

while ((line = rdr.readLine()) != null) {
System.out.println(line+"\n");
}
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Dundonald said:
Has anyone got a sample code or utility that will allow a POST request
to be created to a SSL/HTTPS url?

I've spent a few hours googling and got solutions for HTTP and those
that I have found for HTTPs haven't worked.

Here are a small working example:

package october;

import 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(sslctx.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];
}
}

Arne
 
D

Dundonald

Dundonald said:
Has anyone got a sample code or utility that will allow a POST request
to be created to a SSL/HTTPS url?
I've spent a few hours googling and got solutions for HTTP and those
that I have found for HTTPs haven't worked.

Here are a small working example:

package october;

import 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(sslctx.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];
}

}

Arne

Thanks I'll give it a try. Instead of System.out.println(line); what's
the best way of sending the HTML response back to browser?
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Dundonald said:
....
Thanks I'll give it a try. Instead of System.out.println(line); what's
the best way of sending the HTML response back to browser?

It is in servlet/JSP context ?

JSP out and servlet response.getWriter has a println method.

Arne
 
G

Guest

Lew said:
The examples do not indicate so. The answer for the OP may well be to
go with JEE instead of the JSE approach.

????

"send HTML back to browser" indicates that it is JSP or servlet
context.

And the JEE way is the same as the JSE way.

Arne
 
L

Lew

Arne said:
????

"send HTML back to browser" indicates that it is JSP or servlet
context.

And the JEE way is the same as the JSE way.

The OP's code and original post gave no hint that they were interested in
working with a browser; it was only in a followup that they mentioned using a
browser.

Using JEE, I have never had to manually create an HTTPS socket. The usual
approach, which is what I meant by the "JEE way", is to write a servlet and
mount it in a servlet container. Doing it outside the container, manually
establishing the connection, I call the "JSE way" - there is no use in the
OP's code snippets of any of the JEE SDK.

So, no, they are not the same.
 
G

Guest

Lew said:
The OP's code and original post gave no hint that they were interested
in working with a browser; it was only in a followup that they mentioned
using a browser.

Using JEE, I have never had to manually create an HTTPS socket. The
usual approach, which is what I meant by the "JEE way", is to write a
servlet and mount it in a servlet container. Doing it outside the
container, manually establishing the connection, I call the "JSE way" -
there is no use in the OP's code snippets of any of the JEE SDK.

So, no, they are not the same.

Try actually read what has been posted in the thread.

This is HTTP client code not HTTP server code.

browser--(HTTP)--JSP/servlet--(HTTP)--some other web server

You write HTTP client code in JEE exactly the same way as
you do in JSE, because there are no relevant classes
in JEE.

That you have never written such code is not particular
relevant.

Many others have. My guess is that you can find thousands of
code snippets doing so on the net.

This was a little bit special because it was HTTPS and POST.

Arne
 
L

Lew

Arne said:
Try actually read what has been posted in the thread.

This is HTTP client code not HTTP server code.

browser--(HTTP)--JSP/servlet--(HTTP)--some other web server

You write HTTP client code in JEE exactly the same way as
you do in JSE, because there are no relevant classes
in JEE.

That you have never written such code is not particular
relevant.

Many others have. My guess is that you can find thousands of
code snippets doing so on the net.

This was a little bit special because it was HTTPS and POST.

Your points are well taken.
 
G

Guest

Lew said:
Except for one thing - if the person is writing client code, what
browser are they referring to?

browser--(HTTP)--JSP/servlet--(HTTP)--some other web server
^
code here

It is HTTP client to the other web server.

Output can be send back to the browser either as-is or
modified.

The middle part is also a HTTP server, but I will not call
the JSP/servlet that because the server part is in the
container.

Arne
 
L

Lew

browser--(HTTP)--JSP/servlet--(HTTP)--some other web server
^
code here

It is HTTP client to the other web server.

Output can be send back to the browser either as-is or
modified.

The middle part is also a HTTP server, but I will not call
the JSP/servlet that because the server part is in the
container.

Aha!

Thank you.
 
G

Guest

Lew said:

At least that is how I interpreted the code and reference
to browser.

There is always the possibility that I completely
misunderstood everything.

Arne
 
D

Dundonald

At least that is how I interpreted the code and reference
to browser.

There is always the possibility that I completely
misunderstood everything.

Arne

Sorry to come back with this but I really have been spending hours on
this today and I'm just not quite there.

I've tried many solutions and got them working for POST HTTP but HTTPS
just isn't there.

Arne I tried your solution and I couldn't get it to work, and to be
honest it was over a few hours ago now since I tried so I can't
remember which one out of the many attempts and error messages I got
today, sorry.

I've done even more googling and came across the jakarta commons
httpclient package (http://jakarta.apache.org/httpcomponents/
httpclient-3.x/) and decided to give that a go. This package handles
both HTTP and HTTPS.

Again I tried it with HTTP and it worked great (see code below). I
then switched to a HTTPS connection and I get an
SSLHandshakeException, top few lines of stack trace here ...

[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R Fatal transport
error: unknown certificate
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R
javax.net.ssl.SSLHandshakeException: unknown certificate
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R at
com.ibm.jsse.bg.a(Unknown Source)
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R at
com.ibm.jsse.b.a(Unknown Source)
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R at
com.ibm.jsse.b.write(Unknown Source)
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R at
java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:81)
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R at
java.io.BufferedOutputStream.flush(BufferedO

So I do some more googling and I read about adding these two lines:

System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

which I do to the top of the code below and I then get a different
exception - example stack trace top few lines here ...

[06/10/07 23:28:32:562 BST] 69b640f1 WebGroup E SRVE0026E:
[Servlet Error]-[Cipher buffering error in JCE provider IBMJCE]:
java.lang.RuntimeException: Cipher buffering error in JCE provider
IBMJCE
at com.sun.net.ssl.internal.ssl.CipherBox$JCECipherBox.a(DashoA12275)
at com.sun.net.ssl.internal.ssl.OutputRecord.a(DashoA12275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA12275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA12275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA12275)

why is it so difficult to connect to SSL?

Any help really appreciated. Thanks.

-------------------

My code:

HttpClient client = new HttpClient();
PostMethod post = new PostMethod("https://somesecureurl.com");

NameValuePair[] data = {
new NameValuePair("name1", "value1"),
....
new NameValuePair("nameX","valueX")
};

post.setRequestBody(data);

try
{
// Execute the method.
int statusCode = client.executeMethod(post);

if (statusCode != HttpStatus.SC_OK)
{
System.err.println("Method failed: " + post.getStatusLine());
}

// Read the response body.
byte[] responseBody = post.getResponseBody();

// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
data
out.println(new String(responseBody));
}
catch (HttpException e)
{
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();

}
catch (IOException e)
{
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
}
finally
{
// Release the connection.
post.releaseConnection();
}
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Dundonald said:
Arne I tried your solution and I couldn't get it to work, and to be
honest it was over a few hours ago now since I tried so I can't
remember which one out of the many attempts and error messages I got
today, sorry.

I tested it before posting so it is a working example.
I've done even more googling and came across the jakarta commons
httpclient package (http://jakarta.apache.org/httpcomponents/
httpclient-3.x/) and decided to give that a go. This package handles
both HTTP and HTTPS.

It solves problems with maintaining session and handling
redirects etc..

But for a simple HTTPS it should neither be necessary or
make a difference.
Again I tried it with HTTP and it worked great (see code below). I
then switched to a HTTPS connection and I get an
SSLHandshakeException, top few lines of stack trace here ...

[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R Fatal transport
error: unknown certificate
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R
javax.net.ssl.SSLHandshakeException: unknown certificate

That sounds as a certificate problem. Exactly what my code was handling.
So I do some more googling and I read about adding these two lines:

System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Referring directly to com.sun classes should not be necessary.
which I do to the top of the code below and I then get a different
exception - example stack trace top few lines here ...

[06/10/07 23:28:32:562 BST] 69b640f1 WebGroup E SRVE0026E:
[Servlet Error]-[Cipher buffering error in JCE provider IBMJCE]:
java.lang.RuntimeException: Cipher buffering error in JCE provider
IBMJCE

IBMJCE ??

Are your working with an IBM Java ?
why is it so difficult to connect to SSL?

It is really not that difficult.

Arne
 
D

Dundonald

Dundonald said:
Arne I tried your solution and I couldn't get it to work, and to be
honest it was over a few hours ago now since I tried so I can't
remember which one out of the many attempts and error messages I got
today, sorry.

I tested it before posting so it is a working example.
I've done even more googling and came across the jakarta commons
httpclient package (http://jakarta.apache.org/httpcomponents/
httpclient-3.x/) and decided to give that a go. This package handles
both HTTP and HTTPS.

It solves problems with maintaining session and handling
redirects etc..

But for a simple HTTPS it should neither be necessary or
make a difference.
Again I tried it with HTTP and it worked great (see code below). I
then switched to a HTTPS connection and I get an
SSLHandshakeException, top few lines of stack trace here ...
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R Fatal transport
error: unknown certificate
[06/10/07 23:25:32:062 BST] 5d9100f1 SystemErr R
javax.net.ssl.SSLHandshakeException: unknown certificate

That sounds as a certificate problem. Exactly what my code was handling.
So I do some more googling and I read about adding these two lines:
System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Referring directly to com.sun classes should not be necessary.
which I do to the top of the code below and I then get a different
exception - example stack trace top few lines here ...
[06/10/07 23:28:32:562 BST] 69b640f1 WebGroup E SRVE0026E:
[Servlet Error]-[Cipher buffering error in JCE provider IBMJCE]:
java.lang.RuntimeException: Cipher buffering error in JCE provider
IBMJCE

IBMJCE ??

Are your working with an IBM Java ?
why is it so difficult to connect to SSL?

It is really not that difficult.

Arne

Arne - thanks for your replies, much appreciated.

Here's an exception that I got from running your code:

java.security.NoSuchAlgorithmException: Algorithm SSL not available
at javax.net.ssl.SunJSSE_b.a(DashoA6275)
at javax.net.ssl.SSLContext.getInstance(DashoA6275)
at october.HttpsPost.main(HttpsPost.java:11)
Exception in thread "main"

Line 11 = SSLContext sslctx = SSLContext.getInstance("SSL");
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Dundonald said:
Here's an exception that I got from running your code:

java.security.NoSuchAlgorithmException: Algorithm SSL not available
at javax.net.ssl.SunJSSE_b.a(DashoA6275)
at javax.net.ssl.SSLContext.getInstance(DashoA6275)
at october.HttpsPost.main(HttpsPost.java:11)
Exception in thread "main"

Line 11 = SSLContext sslctx = SSLContext.getInstance("SSL");

What version of Java ?

You can try the alternatives:

SSLv2
SSLv3
TLS
TLSv1
TLSv1.1

Arne
 
D

Dundonald

Dundonaldwrote:



What version of Java ?

You can try the alternatives:

SSLv2
SSLv3
TLS
TLSv1
TLSv1.1

Arne

Arne, no need for alternatives. I was running WSAD IDE using JDK 1.3
with patched on JSSE and JCE jars, and have since changed to netbeans
with JDK 5 and retried your code and it works. Thanks.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Dundonald said:
no need for alternatives. I was running WSAD IDE using JDK 1.3
with patched on JSSE and JCE jars, and have since changed to netbeans
with JDK 5 and retried your code and it works. Thanks.

If I were to guess I would guess on IBM Java 1.3.1 and some
SUN JSSE & JCE, which could be a tricky combo.

But if you can use SUN Java 1.5, then by all means do it. Java 1.3
is very old.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top