Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

POST request to SSL/HTTPS URL

Thread view: 
Dundonald - 06 Oct 2007 14:19 GMT
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.
Dundonald - 06 Oct 2007 14:57 GMT
> 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");
}
Arne Vajhøj - 06 Oct 2007 15:07 GMT
> 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
Dundonald - 06 Oct 2007 15:19 GMT
On Oct 6, 3:07 pm, Arne Vajh?j <a...@vajhoej.dk> wrote:
> > Has anyone got a sample code or utility that will allow a POST request
> > to be created to a SSL/HTTPS url?
[quoted text clipped - 58 lines]
>
> 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?
Arne Vajhøj - 06 Oct 2007 16:05 GMT
>>> 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:
...
> 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
Lew - 06 Oct 2007 19:09 GMT
>>>> Has anyone got a sample code or utility that will allow a POST request
>>>> to be created to a SSL/HTTPS url?
[quoted text clipped - 6 lines]
>
> It is in servlet/JSP context ?

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

Signature

Lew

Arne Vajhøj - 06 Oct 2007 19:18 GMT
>>>>> Has anyone got a sample code or utility that will allow a POST request
>>>>> to be created to a SSL/HTTPS url?
[quoted text clipped - 9 lines]
> 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
Lew - 06 Oct 2007 19:43 GMT
>>>>>> Has anyone got a sample code or utility that will allow a POST
>>>>>> request
[quoted text clipped - 17 lines]
>
> 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.

Signature

Lew

--
Lew

Arne Vajhøj - 06 Oct 2007 20:25 GMT
>>>>>>> Has anyone got a sample code or utility that will allow a POST
>>>>>>> request
[quoted text clipped - 29 lines]
>
> 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
Lew - 06 Oct 2007 20:53 GMT
> Try actually read what has been posted in the thread.
>
[quoted text clipped - 13 lines]
>
> This was a little bit special because it was HTTPS and POST.

Your points are well taken.

Signature

Lew

Lew - 06 Oct 2007 20:53 GMT
>> Try actually read what has been posted in the thread.
>>
[quoted text clipped - 15 lines]
>
> Your points are well taken.

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

Signature

Lew

Arne Vajhøj - 06 Oct 2007 21:40 GMT
>>> Try actually read what has been posted in the thread.
>>>
[quoted text clipped - 18 lines]
> 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
Lew - 06 Oct 2007 21:45 GMT
Lew wrote:
>> 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
>                      ^
[quoted text clipped - 8 lines]
> the JSP/servlet that because the server part is in the
> container.

Aha!

Thank you.

Signature

Lew

Arne Vajhøj - 06 Oct 2007 22:41 GMT
> Lew wrote:
>>> Except for one thing - if the person is writing client code, what
[quoted text clipped - 14 lines]
>
> Aha!

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

There is always the possibility that I completely
misunderstood everything.

Arne
Dundonald - 06 Oct 2007 23:29 GMT
> > Lew wrote:
> >>> Except for one thing - if the person is writing client code, what
[quoted text clipped - 22 lines]
>
> 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();
}
Arne Vajhøj - 07 Oct 2007 20:29 GMT
> 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
[quoted text clipped - 4 lines]
> [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 ...
[quoted text clipped - 3 lines]
> 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
Dundonald - 08 Oct 2007 00:09 GMT
> > 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
[quoted text clipped - 50 lines]
>
> 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");
Arne Vajhøj - 08 Oct 2007 01:51 GMT
> Here's an exception that I got from running your code:
>
[quoted text clipped - 5 lines]
>
> Line 11 = SSLContext sslctx = SSLContext.getInstance("SSL");

What version of Java ?

You can try the alternatives:

SSLv2
SSLv3
TLS
TLSv1
TLSv1.1

Arne
Dundonald - 09 Oct 2007 18:54 GMT
> Dundonaldwrote:
> > Here's an exception that I got from running your code:
[quoted text clipped - 18 lines]
>
> 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.
Arne Vajhøj - 10 Oct 2007 01:15 GMT
>> Dundonaldwrote:
>>> Here's an exception that I got from running your code:
[quoted text clipped - 16 lines]
> 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
Roedy Green - 10 Oct 2007 14:21 GMT
>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.

I understand that all you do is use a https: instead of http:

Try the code posted at http://mindprod.com/products1.html#HTTP
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.