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 / November 2005

Tip: Looking for answers? Try searching our database.

Access to an https page with certificate

Thread view: 
Alessandro Rossi - 16 Nov 2005 16:59 GMT
Hi
I'm writing a class which tries to access to an https web page which
has an user/password and a certificate. I need to access to this page
programmaticaly because I have to post some data looping a set of data.
The probelm is that I receive an error and my code doesn't work. My
question is: If I haven't the certificate installed on my PC, Can I
access to this page with my class? And if this is possible, who can
help me? :) Thank you in advance.

/**
*
*/
package mypackage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.URLStreamHandlerFactory;
import java.security.KeyStore;
import java.security.Security;
import java.util.Properties;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
* @author me
*
*/
public class PostQuery {

    /**
    *
    */
    public PostQuery() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PostQuery postQuery = new PostQuery();
        URL url;
        try {
            url = new URL("https://user:password@www.myaddresspage");

            try {
                postQuery.getResponse(url, "mydata");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public String getResponse (URL _url, String _request)throws
Exception{
        HttpsURLConnection c = null;
         InputStream is = null;
         OutputStream os = null;
         // b is to collect the repsonse from the server
         StringBuffer b = new StringBuffer( );

           // Create a trust manager that does not validate certificate
chains
           TrustManager[] trustAllCerts = new TrustManager[]{
               new X509TrustManager() {
                   public java.security.cert.X509Certificate[]
getAcceptedIssuers() {
                       return null;
                   }
                   public void checkClientTrusted(
                       java.security.cert.X509Certificate[] certs, String
authType) {
                   }
                   public void checkServerTrusted(
                       java.security.cert.X509Certificate[] certs, String
authType) {
                   }
               }
           };

           // Install the all-trusting trust manager
           try {
               SSLContext sc = SSLContext.getInstance("SSL");
               sc.init(null, trustAllCerts, new
java.security.SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
           } catch (Exception e) {
           }

         // open the connection
          c = (HttpsURLConnection)_url.openConnection();
           c.setDoOutput(true);
           c.setDoInput(true);
           //  set the method (i.e. GET or POST)
           c.setRequestMethod("POST");

           // get the output stream - this is for writing the post data to
           os = c.getOutputStream();
           // write the data
           os.write(_request.getBytes());

           os.flush();
           os.close();
           // Get HTTP response
           is = c.getInputStream( );
           System.out.println("Response code = "+ c.getResponseCode());
           int ch;
           while ((ch = is.read( )) != -1){
             b.append((char) ch);
           }
           is.close();
           c.disconnect();
           // b contains the data returned from the server
           return(b.toString());
    }
}

I receive "Server returned HTTP response code: 401"

Bye
Alessandro
IchBin - 16 Nov 2005 17:48 GMT
> Hi
> I'm writing a class which tries to access to an https web page which
[quoted text clipped - 4 lines]
> access to this page with my class? And if this is possible, who can
> help me? :) Thank you in advance.

[snip code]

> I receive "Server returned HTTP response code: 401"
>
> Bye
> Alessandro

Are you behind a firewall? Could be a firewall, proxy or ZoneAlarm...
etc problem.

Signature

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Alessandro Rossi - 17 Nov 2005 07:44 GMT
Yes , there is a firewall, but you think the code is right?

Thank you
Ale
Alessandro Rossi - 17 Nov 2005 08:00 GMT
Ah, I would like add that if I access the page from a browser ( from
the same computer where the class is running), this works properly. It
asks me to accept the certificate, and then, if I accept it gives me a
prompt to set the user and the password. Entering the right user and
pwd I can access to the page...

Ale
abrasivesponge@gmail.com - 16 Nov 2005 19:03 GMT
You may wanna try an authenticator too
http://javaalmanac.com/egs/java.net/Auth.html
Alessandro Rossi - 17 Nov 2005 07:47 GMT
I tried, but it gives me this error when I execute:
BufferedReader in = new BufferedReader(new
InputStreamReader(url.openStream()));

sun.security.validator.ValidatorException: PKIX path validation failed:
java.security.cert.CertPathValidatorException: basic constraints check
failed: this is not a CA certificate

Thank you
Ale
Alexey Osyatnikov - 17 Nov 2005 08:35 GMT
Hi,
Have you considered using Apache Commons HTTP client for this?
It supports authentication, proxies and has a number of contributed classes
as well.
There you can find examples of different TrustManagers (your version will
have an empty checkClientCert and checkServerCert methods if you don't want
to validate certificates)

> Hi
> I'm writing a class which tries to access to an https web page which
[quoted text clipped - 141 lines]
> Bye
> Alessandro
Rogan Dawes - 17 Nov 2005 08:46 GMT
> Hi
> I'm writing a class which tries to access to an https web page which
[quoted text clipped - 4 lines]
> access to this page with my class? And if this is possible, who can
> help me? :) Thank you in advance.

> I receive "Server returned HTTP response code: 401"
>
> Bye
> Alessandro

401 is the server returning an "Unauthorised" response.

I'm not sure if Java actually supports the "user:password@url" notation.

You may need to add an "Authorization: Basic " +
base64(username:password) header to authenticate yourself to the server.

Or possibly the Url class has some specific support for this.

Rogan


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



©2009 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.