Problem in HttpsURLConnection

I am trying to make HttpsURLConnection, but I got javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found exception.
I included my code here
If u find anything wrong here, please let me know
System.setProperty("javax.net.debug","all");
System.setProperty("UseSunHttpHandler", "true");
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "my proxy ip");
System.setProperty("http.proxyPort", "80");
System.setProperty("java.protocol.handler.pkgs","javax.net.ssl");
String c_keystore = "madhu.keystore";
System.setProperty("javax.net.ssl.keyStore",c_keystore);
System.setProperty("javax.net.ssl.keyStorePassword","madhu123");
System.setProperty("javax.net.ssl.trustStore",c_keystore);
System.setProperty("javax.net.ssl.trustStorePassword","madhu123");
com.sun.net.ssl.internal.ssl.Provider.install();
java.security.Security.insertProviderAt(new com.sun.net.ssl.internal.ssl.Provider(), 1);
//URL url = new URL("https://myhostname/myfile.jsp");
URL url = new URL(null, "https://myhostname/myfile.jsp", new com.sun.net.ssl.internal.www.protocol.https.Handler());
HttpsURLConnection urlConn; //I tried with HttpURLConnection also
DataOutputStream printout;
BufferedReader input;
String content = "loginname=neonlines&password=password";
System.out.println("OPEN CONNECTION");
urlConn = (HttpsURLConnection)url.openConnection(); //I tried with HttpURLConnection also
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod("POST");
urlConn.setFollowRedirects(true);
/******************** I commented the following lines - No need for me as of now *************
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.setRequestProperty("Content-length", String.valueOf(content.length()));
System.out.println("OUTPUT STREAM");
printout = new DataOutputStream(urlConn.getOutputStream());
printout.writeBytes(content);
printout.flush();
******************** I commented the above lines - No need for me as of now *************/
System.out.println("READ INPUT STREAM");
input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); //EXCEPTION IN THIS LINE
String str;
String line = "";
System.out.println("PRINTING THE PAGE ");
while((str = input.readLine()) != null) {
     System.out.println(str);
     line += str;
I added the keystore "madhu.keystore" using keytool from x509 (extension cer)
I got the following exception
xecuteThread: '19' for queue: 'weblogic.kernel.Default', SEND TLSv1 ALERT: fatal, description = certificate_unknown
ExecuteThread: '19' for queue: 'weblogic.kernel.Default', WRITE: TLSv1 Alert, length = 2
ExecuteThread: '19' for queue: 'weblogic.kernel.Default', called closeSocket()
ExecuteThread: '19' for queue: 'weblogic.kernel.Default', handling exception: javax.net.ssl.SSLHandshakeException: sun.security.vali
dator.ValidatorException: No trusted certificate found
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SunJSSE_az.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SunJSSE_az.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SunJSSE_ax.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.j(DashoA6275)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(DashoA6275)
at sun.net.www.protocol.https.HttpsClient.afterConnect(DashoA6275)
more
Please let me know where I 'm doing wrong.

I solved the problem by myself.
I dynamically installed the certificate using TrustManagerFactory and now it's working fine

Similar Messages

  • Tunneling Problem using HttpsUrlConnection

    Hi,
    I had gone through forums regarding this topic and still i am facing the same problem using the HttpsUrlConnection. We are working behind a proxy so we have to make a proxy authorization if we want to connect to a server in the internet.
    But in case of HttpUrlConnection, everything works
    fine. But if we do the same with a HttpsUrlConnection, the authentication fails. It throws an IOException
    with the message
    Unable to tunnel through 192.9.100.10:80.
    Proxy returns "HTTP/1.1 407 Proxy authentication required"
    Sample code as follows,
    The following code doesn't have any problem becos it works fine with HttpUrlConnection and also it is working without proxyserver for https as well.
    This is running under MSVM.
    I don't want to use SSLSocketFactory and i need to use following layout(i.e only with Httpsurlconnection)
    Is there any way to make work with proxyserver? Or can't we do this at all?
    System.setProperty("proxySet","true");
    System.setProperty("https.proxyHost","proxyIP");
    System.setProperty("https.proxyPort","80");
    OutputStream os = null;
    OutputStreamWriter osw = null;
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    URL url;
    String line = null;
    System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    String login = proxyUserName+":"+proxyPassWord;
    String encodedLogin = new sun.misc.BASE64Encoder().encode(login.getBytes());
    url = new URL("https://www.verisign.com");
    HttpsURLConnection con = null;
    con =(HttpsURLConnection) url.openConnection();
    con.setRequestProperty("Proxy-Authorization", encodedLogin);
    con.setRequestMethod("GET");
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);
    con.connect();
    os = con.getOutputStream();
    osw = new OutputStreamWriter(os);
    osw.write("SampleMsg");
    osw.flush();
    osw.close();
    is = con.getInputStream();
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    while ( (line = br.readLine()) != null)
         System.out.println("line: " + line);
    Can any one help me regarding this?I need a reply very urgently.
    Thanks,
    Prabhakaran R

    Hope this help.
    Note to change the properties to fit your system, and use the supported package ( JSSE, JRE1.5.......).
    You can use URLConnection for both HTTP or HTTPS protocol.
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.util.*;
    import javax.net.ssl.*;
    public class testSSL9 {
    public testSSL9() {
    byte[] data = httpConnection();
    System.out.println(new String(data));
    public static void main(String[] args) {
    Properties sysprops = System.getProperties();
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // sysprops.put("java.protocol.handler.pkgs",
    // "com.sun.net.ssl.internal.www.protocol");
    sysprops.put("java.protocol.handler.pkgs",
    "javax.net.ssl.internal.www.protocol");
    sysprops.put("javax.net.ssl.trustStore",
    "D:/jdk1.4/jre/lib/security/cacerts");
    sysprops.put("javax.net.debug", "ssl,handshake,data,trustmanager");
    sysprops.put("https.proxyHost", "172.16.0.1");
    sysprops.put("https.proxyPort", "3128");
    sysprops.put("https.proxySet", "true");
    sysprops.put("http.proxyHost", "172.16.0.1");
    sysprops.put("http.proxyPort", "3128");
    sysprops.put("proxySet", "true");
    testSSL9 testSSL91 = new testSSL9();
    private byte[] httpConnection() {
    try {
    URL url = null;
    // String strurl = "https://www.verisign.com";
    String strurl = "https://central.sun.net";
    // String strurl = "http://www.yahoo.com"; --> use: HttpURLConnection
    url = new URL(strurl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    HttpsURLConnection.setFollowRedirects(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.connect();
    InputStream stream = null;
    BufferedInputStream in = null;
    ByteArrayOutputStream bytearr = null;
    BufferedOutputStream out = null;
    try {
    stream = connection.getInputStream();
    in = new BufferedInputStream(stream);
    bytearr = new ByteArrayOutputStream();
    out = new BufferedOutputStream(bytearr);
    catch (Exception ex1) {
    System.out.println(ex1);
    System.out.println("Server reject connection...sory");
    int i = 0;
    while ( (i = in.read()) != -1) {
    out.write(i);
    out.flush();
    stream.close();
    in.close();
    bytearr.close();
    out.close();
    return bytearr.toByteArray();
    catch (Exception ex) {
    ex.printStackTrace();
    return null;
    }

  • Problem with HttpsURLConnection

    Hello,
    I have a problem when I use HttpsURLConnection. I have this code:
    import java.security.*;
    import com.sun.net.ssl.*;
    import javax.net.ssl.*;
    import javax.net.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.net.ssl.HttpsURLConnection;
    public class ConexionPrueba
         public static void main (String[] args) {
         try {
              URL URL = new URL("https://194.140.2.144:7002/recepcionXML/recepcionLOC");
              System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
              java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
              javax.net.ssl.HttpsURLConnection HttpCon = (javax.net.ssl.HttpsURLConnection) URL.openConnection();
              System.out.println("me he conectado a: " + HttpCon.toString());
              HttpCon.setDoOutput( true );
              HttpCon.setDoInput( true );
    HttpCon.setRequestMethod( "POST" );
    HttpCon.setRequestProperty("server-protocol", "HTTP/1.1");
    HttpCon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    HttpCon.setUseCaches(false);
    FileWriter fd = new FileWriter("resultado_localizacion.xml");
    BufferedReader bufferInput = null;
    bufferInput = new BufferedReader(new InputStreamReader(HttpCon.getInputStream()));
    String str = bufferInput.readLine();
    while (str != null) {
    fd.write(str);      
         if (str.equals("</GPPM_IT>"))
         break;
    str = bufferInput.readLine();
         } catch (SSLHandshakeException e2) {
              e2.printStackTrace();
         }catch (Exception e) {
              e.printStackTrace();
    public ConexionPrueba() {}
    public void conectar() {
    try {
         // System.getProperties().setProperty("java.protocol.handler.pkgs", "HTTPClient");
         //String resultado = (String) System.getProperties().get("java.protocol.handler.pkgs");
         //System.out.println("resultado es: " + resultado);
    //Handler handler = new Handler();
    //System.out.println("creando el handler: " + handler.toString());
         URL httpURL = new URL("https://194.140.2.144:7002/recepcionXML/recepcionLOC?CLIENT=patricia&CLIENT_PASSWD=patricia&USERID=34678625168&USERID_TYPE=MSISDN");
         Conectar conectar = new Conectar(httpURL);
         conectar.connect();
         System.out.println("la url a la que voya a llamar es: " + httpURL.toString());
         // System.out.println("estoy pasando despues de crear la url");
    //URLConnection con = handler.openConnection(httpURL);
    //System.out.println("pasando por detras de URLConnection");
    //HTTPConnection con = new HTTPConnection("https", "https://194.140.2.144:7002/recepcionXML/recepcionLOC?CLIENT=patricia&CLIENT_PASSWD=patricia&USERID=34678625168&USERID_TYPE=MSISDN", -1);
    //      HTTPConnection con = new HTTPConnection(httpURL);
    //System.out.println("pasando despues de abrir una URL Connection");
    //HTTPConnection con = new HTTPConnection(httpURL);
    //Cogemos por post lo que hay en el response
    HTTPResponse rsp = con.Post("c:/jswdk101/jswdk-1.0.1/respuesta_localizacion.xml");
    //URLConnection con = httpURL.openConnection();
    //      System.out.println("intentando conectarme....");
    // con.setDoInput(true);
    // con.setDoOutput(true);
    * Recojo el fichero que me ha enviado Localizacion
    /* FileWriter fd = new FileWriter(fichero_salida);
    // Recojo la respuesta del servlet
    BufferedReader bufferInput = null;
    // bufferInput = new BufferedReader(new InputStreamReader(con.getInputStream()));
    bufferInput = new BufferedReader(new InputStreamReader(rsp.getInputStream()));
    String str = bufferInput.readLine();
    while (str != null) {
    fd.write(str);      
         if (str.equals("</GPPM_IT>"))
         break;
         str = bufferInput.readLine();
    } catch (Exception e){
    e.printStackTrace();
    When i run this class, I have this exception:
    javax.net.ssl.SSLHandshakeException: Couldn't find trusted certificate
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.b(DashoA6275)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.a(DashoA6275)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(DashoA6275)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(DashoA6275)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(DashoA6275)
    at com.sun.net.ssl.internal.ssl.AppOutputStream.write(DashoA6275)
    at java.io.OutputStream.write(OutputStream.java:58)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(DashoA6275)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(DashoA6275)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(DashoA6275)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:562)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(DashoA6275)
    at ConexionPrueba.main(ConexionPrueba.java:35)
    I hope that you can help me. Thanks,
    Patricia

    Try reading this documentation: http://developer.java.sun.com/developer/technicalArticles/Security/secureinternet2/

  • Problem with HttpsURLConnection - classcastexception

    i declared url connection from java.net pakage thru weblogic server
    when i am trying to execute following servlet
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.URL;
    public class SimpleServlet extends HttpServlet
    public void doGet (HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    java.net.URL url = new java.net.URL("http:\\www.mail.yahoo.com");
    System.out.println("url class name is -->"+ url.getClass().getName());
    java.net.URLConnection urlc = url.openConnection();
    System.out.println("urlc class name is "+urlc.getClass().getName());
    // System.out.println("url open connection class name is -->"+ url.openConnection().getClass().getName());
    // System.out.println("SimpleServlet 1 ->com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection");
    com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection urlcon = (com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection) url.openConnection();
    System.out.println("class name is .."+urlcon.getClass().getName());
    the out put is showling weblogic class. it should not be, how to set property pkgs.handlers in weblogic
    thanks in advance
    Bala
    [email protected]

    Why didn't you call ResultSet.getDouble(columnIndex) or Resultset.getFloat(columnIndex) in the first place, rather than whatever you did? Then the database driver would have handled the data translation for you instead of making you do all that nasty casting.

  • Weird HttpsURLConnection problem

    Hi everyone,
    I am running a struts application on jboss 3.2.1. Part of my application deals with posting xml over https. Two problems popped up today, and because they appeared at the same time, I have a hunch they're related.
    1. Our production server (which we recently purchased a new SSL certificate for) cannot post xml over https.
    2. All of our testing servers can post xml over https (these are running the exact same code). However, when we try to post to our production server, the code breaks.
    Here is the code that does the posting:
    HostnameVerifier hv = new HostnameVerifier() {
                 public boolean verify(String urlHostName, SSLSession session) {
                     System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());
                     return true;
             HttpURLConnection uc = null;
             if ("https".equals(url.getProtocol())) {
                  HttpsURLConnection.setDefaultHostnameVerifier(hv);
                  uc = (HttpsURLConnection) url.openConnection();
             else {
                  uc = (HttpURLConnection) url.openConnection();
              uc.setDoOutput(true);
            if (!headers.isEmpty()) {
                for (Iterator it = headers.keySet().iterator(); it.hasNext(); ) {
                    String key = (String) it.next();
                    String val = (String) headers.get(key);
                    uc.setRequestProperty(key, val);
            logger.info( uc.getURL().toExternalForm() );
            logger.info( uc.getURL().toString() );
            OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(uc.getOutputStream()), "ASCII");
            out.write(query.toString() + data.toString() + "\r\n");
            out.flush();
            out.close();
            for (int j = 0; ; j++) {
                 String header = null;
                 try {
                      header = uc.getHeaderField(j);
                 catch (Exception e) {
                      logger.error(e);
                logger.info("j = " + j + "; header = " + header );
                if (header == null) {
                    break;
                rHeaders.put(uc.getHeaderFieldKey(j), header);
            rCode = uc.getResponseCode();
            rMsg = uc.getResponseMessage();
            rLastMod = uc.getLastModified();
            inn = uc.getInputStream();
            return inn; While using Eclipse's debugger to step through this code on my local machine (and posting to our production server) to QA problem #2, everything goes fine until the line "header = uc.getHeaderField(j);" No exception is thrown that I can see, but the system hangs, and the debugger stops working. I thought maybe some kind of exception was being thrown (hence the try/catch) but nothing is caught.
    Any ideas what might be the problem? Does this sound like an issue with the cert? It was purchased two weeks ago or so, and is valid from 7/21/2005 to 8/11/2006.
    Any help would be greatly appreciated. Thank you,
    Ben Rainville

    That didn't seem to have any effect.

  • HttpsURLConnection class cast exception problem

    Hy everyone,
    I have next java code to send xml file over https.
    //          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());
              javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
              } catch (Exception e) {
              e.printStackTrace();
              //Make the output file for xml response
              DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_kk-mm-ss");
                   _xmlResponseIme = dateFormat.format(new Date());
                   try {
                        if (createOutXML(_xmlResponseIme)){
                             this.set_xmlResponseIme(_xmlResponseIme);
                   } catch (IOException e2) {
                        //System.out.println("SSLClient :: createOutXML catch");
                        e2.printStackTrace();
              //translate request.xml file to String
              File xmlRequest = new File(_path + "/XMLFiles/request.xml");
              String xmlFile="";
                   try {
                        xmlFile = this.getStringFromXMLFile(xmlRequest);
                   } catch (FileNotFoundException e) {
                        e.printStackTrace();
                   } catch (Exception e) {
                        e.printStackTrace();
                   this.registerMyHostnameVerifier();
                   try {
                   path = "https://"+host+_config.getString("path");
                        url = new URL(path);
                   } catch (MalformedURLException e1) {
                             e1.printStackTrace();
                   try {
                             conn = (javax.net.ssl.HttpsURLConnection) url.openConnection();
                             conn.setRequestMethod("POST");
                             conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=Cp1250");
                             conn.setDoInput(true);
                             conn.setDoOutput(true);
                             //conn.setDefaultUseCaches(false);
                             conn.setRequestProperty("xml", xmlFile);
                             conn.setAllowUserInteraction(true);
                             System.out.println("Response kod = " + conn.getResponseCode());
                   } catch (IOException e2) {
                             e2.printStackTrace();
                   try {
              //receive answer
              InputStream in = conn.getInputStream();
              FileOutputStream fout;
              fout = new FileOutputStream(_xmlOut);
              StringBuffer sb = new StringBuffer();
              Reader reader = new InputStreamReader(in, "Cp1250");
              int c;
              while ((c = in.read()) != -1){
                   sb.append((char) c);
                   fout.write((byte) c);
              String document = sb.toString();
              System.out.println(document);
              fout.close();
              in.close();
                   } catch (IOException e3) {
                        e3.printStackTrace();
    Problem is that on one WebSphere Application Server 6 is everithing OK, but on another I receive error :
    On both server I have same jdk.
    Error 500: com.ibm.net.ssl.internal.www.protocol.https.HttpsURLConnection
    in line
    conn = (javax.net.ssl.HttpsURLConnection) url.openConnection();
    Where is the problem ??

    Sorry, should have been:
    javax.net.ssl.trustStore=path/to/etc/etc/DummyServerTrustFile.jks
    javax.net.ssl.trustStorePassword=WebAS
    Didn't get it to actually work like that though. trustStore & trustStorePassword were always null when I ran my program under WAS5.1.
    Here is what I did. If running from command line using WAS5.1 as JRE, first setup the environment:
    set JAVA_HOME=C:\Program Files\IBM\SDP70\runtimes\base_v51\java\jre
    java -Djava.protocol.handler.pkgs=com.ibm.net.ssl.internal.www.protocol myProgramIndependent of whether running from command line or in RAD7, code in program:
    System.setProperty("javax.net.ssl.trustStore",
    "C:\\Program Files\\IBM\\SDP70\\runtimes\\base_v51\\etc\\DummyServerTrustFile.jks");
    System.setProperty("javax.net.ssl.trustStorePassword","WebAS");(would be better to be able to specify trustStorePassword in WAS than in code though,
    but works as such)
    One can use some other file but I just added the certificate to DummyServerTrustFile.jks.
    Then, unlike I said, one CAN use the HttpsURLConnection, like this:
    com.ibm.net.ssl.internal.www.protocol.https.HttpsURLConnection conn = null;
    URL urli = new URL("https://some.address.com");
    conn = (com.ibm.net.ssl.internal.www.protocol.https.HttpsURLConnection)urli.openConnection();
    Note this uses classes from C:\Program Files\IBM\SDP70\runtimes\base_v51\java\jre\lib\ibmjsseprovider.jar, so it needs to be in classpath when compiling.
    Now this way I didn't get a cast exception from using HttpsURLConnection. The point is one can't instantiate javax.net.ssl.HttpsURLConnection, because RAD7's WAS5.1 can't cast it into its own class (wish it could).
    Also, I still couldn't use the javax.net.ssl.HttpsURLConnection.setHostnameVerifier method, because com.ibm.net.ssl.internal.www.protocol.https.HttpsURLConnection doesn't have it... So the result was pretty much the same as using a HttpURLConnection as I previously instructed. Well, I don't really need that method in practice, but I suppose one might need it in some situation. The IBM URL I quoted said WAS5.1 doesn't really compare DNS host name with the certificate host name though, so I suppose one doesn't need to programmatically set a dummy HostnameVerifier in WAS5.1.

  • Problem with url.openConnection

    Hi everyone. I have created an applet that runs ok in appletviewer. The problem is that if I load it from IE an exception occurs. THis is because, at some point I want to read a file, and I do url.openConnection. The getContentLength() method of the urlconnection then returns -1 instead of the real file's size. I have to notice, that I have created .jar file for my classes and I use signatures for loading my applets in the browser.
    Any ideas?
    Thanx in advance,
    Theodore

    That made sense, so I changed my imports from:
    import com.sun.net.ssl.internal.www.protocol.https.*;
    import com.sun.net.ssl.internal.ssl.*;
    to
    import javax.net.ssl.*;
    and successfully recompiled. It was hopeful at first because It crashed on some permissions. As soon as I corrected the permissions in java.policy, that damn ClassCastException was back.
    Is this still the way to do it using javax.net.ssl?
    System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new sun.security.provider.Sun());
    URL url = new URL(authurl);
    HttpsURLConnection connection = HttpsURLConnection)url.openConnection();
    Thanks for your time...

  • Can't get any response from HttpsURLConnection

    sorry, i've reformat the code here again
    Deal frens,
    Currently i'm doing a code to get a response from https link in my servlet. I don't know where the lack of my coding, but i don't get any response from the server when i execute my code. here is my code
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.net.ssl.*;
    public class Servlet1 extends HttpServlet {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public void init() throws ServletException {
      //Process the HTTP Get request
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        String authentURL = "https://server1.tst.cvs/servlet/RequestHandler?login=admin&pwd=admin&method=viewUser&username=00032a0183db";
        out.println("<html>");
        out.println("<head><title>Servlet1</title></head>");
        URL url = new URL(authentURL);
        HttpsURLConnection URLconn = (HttpsURLConnection) url.openConnection();
       // HttpsURLConnection conn = null;
        URLconn.setDoInput(true);
        URLconn.setDoOutput(true);
        URLconn.setRequestMethod("GET");
        URLconn.setUseCaches(false);
        OutputStream authOut = URLconn.getOutputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(URLconn.getInputStream()));
        out.println("<body bgcolor=\"#ffffff\">");
        out.println("<p>The servlet has received a GET. This is the reply.</p>");
        out.println("output"+authOut);
        out.println("output2"+URLconn.getContent().toString());
        out.println("output3"+reader);
        out.println("</body></html>");
      //Clean up resources
      public void destroy() {
    } the result suppose i get when i execute the script is..
    userdata=234&uname=00032a0183db&concurrentlogins=1
    i don't have any problem when i paste the link
    https://server1.tst.cvs/servlet/RequestHandler?login=admin&pwd=admin&method=viewUser&username=00032a0183db
    and i able to get the response
    userdata=234&uname=00032a0183db&concurrentlogins=1
    please..please help..what is wrong with my code

    YOU DON'T READ ANYTHING IN YOUR CURRENT CODE !!!
    If you use a BufferedReader, then read the input stream via readLine() method.
    Default implementation of getContent() method is not generally usable for getting your desired "content". Experiment that.

  • FileNotFound exception from getInputStream of HttpsURLConnection

    All,
    I'm in a bad way here and can use any input you may have. In our production application on Weblogic 8.1 SP 6, we have the following exception being thrown in the getInputStream() of an open weblogic.net.http.HttpsURLConnection:
    java.io.FileNotFoundException: Response: '500: Internal Server Error' for url: 'https://xxxxxxxxxxxxx'
    The problem is intermittent but has been recently occurring with great frequency. The only difference in tcpdumps of sunny day vs. this error scenario seems to be that our system (client) does not send a FIN (connection termination) after receiving data from the server in the error scenario. As the data is encrypted, I can't see precisely what the server is passing back. The server that we are connected to has no detailed logging and I cannot answer the immediate question "Is this a client side problem or server side problem?". Any assistance would be greatly appreciated.
    thanks - Dan

    Hi,
              did you place setWLSEnv in your path ?
              ----Anilkumar kari

  • Need help with Casting to HttpsURLConnection

    Can anyone see why this simple cast will not work for me?
    Thanks.
    Here's the error message I get when I try to run it:
    C:\myJava\code\Source>java TestHttpsClientPost
    We have successfully initialized the default SSLSocketFactory!
    java.lang.ClassCastException
    at TestHttpsClientPost.openURLConn(TestHttpsClientPost.java:47)
    at TestHttpsClientPost.callBasicTest(TestHttpsClientPost.java:64)
    at TestHttpsClientPost.main(TestHttpsClientPost.java:86)
    Done with basictest.
    Here's the code, with two methods, a constructor and main:
    import java.io.*;
    import java.net.*;
    import javax.net.ssl.*;
    public class TestHttpsClientPost
    //class variables:
    public static String enc = "UTF-8";
    // THE URL CONNECTION ATTRIBUTES:
    private URL url;
    private HttpsURLConnection urlConn;
    public TestHttpsClientPost() // THE CLASS CONSTRUCTOR:
    // MAKE SURE SSL CAN BE HANDLED
    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // CREATE AN SSL FACTORY THAT WILL TRUST ALL SERVER CERTIFICATES
    try
    javax.net.ssl.SSLSocket sock = null;
    TrustManager[] tma = ( new TrustManager[]
    { new MyTrustManager() }
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,tma,new java.security.SecureRandom());
    SSLSocketFactory sf1 = sc.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sf1);
    System.out.print( "We have successfully initialized the default SSLSocketFactory!\n" );
    } catch(Exception e)
    e.printStackTrace();
    private void openURLConn(String pUrlAddress)
    try
    // SET THE URL TO BE CONNECTED TO:
    url = new URL("https://www.verisign.com");
    // OPEN CONNECTION
    urlConn = (javax.net.ssl.HttpsURLConnection)url.openConnection();
    //HttpsURLConnection urlConn = (HttpsURLConnection)url.openConnection();
    } catch(Exception e)
    e.printStackTrace();
    private void callBasicTest()
    try
    // CONSTRUCT THE POSTSTRING:
    String postString = URLEncoder.encode("function",enc) + "=" + URLEncoder.encode("basictest",enc) +
    "&" + URLEncoder.encode("username",enc) + "=" + URLEncoder.encode("Bob",enc);
    // OPEN A CONNECTION.
    openURLConn(null);
    // POST REQUEST TO URL
    postRequest(postString);
    // WRITE OUTPUT TO STOUT.
    outputResponse(System.out,null);
    // CLOSE CONNECTION
    closeURLConn();
    System.out.println("Done with basictest");
    } catch (Exception e)
    e.printStackTrace();
    public static void main(String[] args) throws Exception
    try
         // CREATE AN INSTANCE OF THIS CLASS.
    TestHttpsClientPost thisClient = new TestHttpsClientPost();
    thisClient.callBasicTest();
    } catch (Exception e)
    e.printStackTrace();

    Thanks again! I get "This is incorrect" when applying your test, which I expected, because I tried to cast using that full path (javax.net.ssl.HttpsURLConnection) and it failed.
    There was a runtime version of java on my computer before I installed the J2SE.... it is in a directory called j2re1.4.1_02. I just left it there when I installed j2sdk1.4.2 in a different directory. Do you think this could cause my problem? I'll can try uninstalling the older runtime version.
    Also, the only thing in my CLASSPATH is a period followed by a semicolon. Is that correct or should I point to a classes directory in j2sdk1.4.2? And, I have nothing in my PATH regarding java.... is that a problem?

  • Problem using multiple Client Certificates

    Hi folks, I had (mistakenly) posted an earlier version of this question to the crypto forum.
    My problem is that I have multiple client certs in my keystore, but only one is being used as the selected certificate for client authentication for all connection�s. So, one connection works fine, the rest fail because the server doesn�t like the client cert being presented.
    I have been trying to get the JSSE to select the proper client certificate by making use of the chooseClientAlias method. (init the SSL context with a custom key manager that extends X509ExtendedKeyManager and implements the inherited abstract method X509KeyManager.chooseClientAlias(String[], Principal[], Socket))
    But, still no luck.. the JSSE is not calling in to the my version of chooseClientAlias, and it just keeps presenting the same client certificate.
    No clue why, any thoughts on how to get the JSSE to call my version of chooseClientAlias?
    Thanks!
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(createCustomKeyManagers(Keystore, KeystorePassword),
                createCustomTrustManagers(Keystore, KeystorePassword),null);
    SSLSocketFactory factory = sslContext.getSocketFactory();
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    urlConn = (HttpsURLConnection) conn;
    urlConn.setSSLSocketFactory(factory);
    BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
         System.out.println(line);  }
    public class CustomKeyManager extends X509ExtendedKeyManager
        private X509ExtendedKeyManager defaultKeyManager;
        private Properties serverMap;
        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
            SocketAddress socketAddress = socket.getRemoteSocketAddress();
            String hostName = ((InetSocketAddress)socketAddress).getHostName().toUpperCase();
            String alias = null;
            if(serverMap.containsKey(hostName)){
                alias = serverMap.getProperty(hostName.toUpperCase());
                if(alias != null && alias.length() ==0){
                    alias = null; }
            else {
                alias = defaultKeyManager.chooseClientAlias(keyType, issuers, socket);
            return alias;
    .

    Topic was correctly answered by ejp in the crypto forum..
    namely: javax.net.ssl.X509KeyManager.chooseClientAlias() is called if there was an incoming CertificateRequest, according to the JSSE source code. If there's an SSLEngine it calls javax.net.ssl.X509ExtendedKeyManager.chooseEngineClientAlias() instead.*
    You can create your own SSLContext with your own X509KeyManager, get its socketFactory, and set that as the socket factory for HttpsURLConnection.*
    Edited by: wick123 on Mar 5, 2008 10:26 AM

  • Soap server connection problem

    in jdeveloper 9.0.2 i am trying to develop and deploy webservice. After starting embeded oc4j engine from the command prompt i m unable to get this url http://<hostname>:8888 from the browser .
    Also facing the problem while running the new soap server connection wizard. while testing the connection i m getting this error.
    Testing connection...
    [SOAPException: faultCode=SOAP-ENV:Protocol; msg=Unsupported response content type "text/html", must be: "text/xml". Response was:
    <HTML><HEAD>
    <TITLE>ERROR: The requested URL could not be retrieved</TITLE>
    </HEAD><BODY>
    <H2>The requested URL could not be retrieved</H2>
    <HR>
    <P>
    While trying to retrieve the URL:
    <A HREF="http://<hostname>:8888/soap/servlet/soaprouter">http://kanti:8888/soap/servlet/soaprouter</A>
    <P>
    The following error was encountered:
    <BLOCKQUOTE>
    Unable to determine IP address from host name for
    <I>kanti</I>
    </BLOCKQUOTE>
    <P>
    The dnsserver returned:
    <BLOCKQUOTE>
    Name Error: The domain name does not exist.
    </BLOCKQUOTE>
    <P>
    This means that:
    <PRE>
    The cache was not able to resolve the hostname presented in the URL.
    Check if the address is correct.
    </PRE>
    <P>Your cache administrator is <A HREF="mailto:root">root</A>.
    <br clear="all">
    <hr noshade size=1>
    Generated Fri, 14 Feb 2003 13:05:51 GMT by firewall (Squid/2.4.STABLE6)
    </BODY></HTML>
         java.lang.String org.apache.soap.rpc.Call.getEnvelopeString(org.apache.soap.transport.SOAPTransport)
         org.apache.soap.rpc.Response org.apache.soap.rpc.Call.invoke(java.net.URL, java.lang.String)
         org.apache.soap.rpc.Response oracle.jdevimpl.webservices.util.JDevServiceManager.invokeMethod(java.lang.String, org.apache.soap.rpc.Parameter)
         java.lang.String[] oracle.jdevimpl.webservices.util.JDevServiceManager.list()
         void oracle.jdevimpl.webservices.wizard.connection.TestConnectionPanel$2.run()
    Unable to connect to SOAPServerConnection1 (http://<hostname>:8888/soap/servlet/soaprouter)
    Connection test failed: unable to connect
    right now i m ready to use any web service either
    1 > j2ee web service .(or)
    2 > soap web service
    but both are not working .
    Pls help me on this issue.
    regards mangesh

    If you use HttpsURLConnection for this, it will work on java 1.4.1, but not on prior releases. It will (as far as I can tell from experiment) use the time that the server provides for Keep-Alive.

  • ClassCastException in HttpsURLConnection

    I try to connect to https://verisign.com using HttpsURLConnection..and i get :
    Exception in thread "main" java.lang.ClassCastException: com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl
         at URLReader.main(URLReader.java:22)
    code:
         java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
         System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
         System.setProperty("javax.net.ssl.trustStore","/home/httpd/servlets/cacerts");
    URL verisign = new URL("https://www.verisign.com/");
    HttpsURLConnection cx =(HttpsURLConnection)verisign.openConnection();
         BufferedReader in = new BufferedReader(
         new InputStreamReader(verisign.openStream()));
         String inputLine;
         while ((inputLine = in.readLine()) != null)
         System.out.println(inputLine);
         in.close();
    Is this problem connected with wrong certificate?
    But why is it a CastException?
    Please help thanks.

    Had this one.
    You probably use the new class:
    javax.net.ssl.HttpsURLConnection and verisign uses
    older com.sun.net.ssl.HttpsURLConnection.

  • Problems with JSSE under Weblogic 5.1 sp9

    I have a java application which uses JSSE to communicate with a WebMethods server
    and it works great. However, when I take the same code block and run it under
    Weblogic 5.1 sp11, I receive a bad certificate error. After spending a lot of
    time reading through various postings, I fixed the problem where Weblogic was
    intercepting HTTPsURLConnection, but still have the bad_certificate error.
    My setup is as follows:
    - Keys stored using keytool in keystores outside of Weblogic
    - Service pack 9 is installed (also tested SP10)
    - Code runs fine as an isolated java application, but will not run when called
    from within weblogic.
    - JDK1.3.1_02
    - Modified the weblogic.policy file with the following line:"permission java.net.NetPermission
    "specifyStreamHandler";"
    Source Code:
    System.getProperties().put("java.protocol.handler.pkgs",
    "com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    System.out.println("\n\nHandler = "+System.getProperty("java.protocol.handler.pkgs"));
    URL server = new URL(null, "https://B2bserver.quadrem.com:4443/invoke/wm.tn/receive",
    new com.sun.net.ssl.internal.www.protocol.https.Handler());
    System.out.println("Connecting to : "+server.toExternalForm());
    char[] password = "weblogic".toCharArray();
    SSLContext context = SSLContext.getInstance("SSL");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream("x:/jpkeystore"), password);
    keyManagerFactory.init(keystore, password);
    context.init(keyManagerFactory.getKeyManagers(), null, null);
    HttpsURLConnection conn = (HttpsURLConnection)server.openConnection();
    conn.setDoInput( true );
    conn.setDoOutput( true );
    conn.setAllowUserInteraction(false);
    conn.setUseCaches( false );
    conn.setDefaultUseCaches ( false );
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","text/xml");
    conn.setRequestProperty("Host", remoteHost);
    conn.setRequestProperty("Content-Length", "" + (XML_HEADER.length()+doc.length()));
    DataOutputStream out = new DataOutputStream (conn.getOutputStream());
    out.writeBytes(XML_HEADER);
    out.write(doc.getBytes());
    out.flush();
    out.close();
    All help will be appreciated.
    thanks
    Mark Johnson
    781-993-9212 x375
    [email protected]

    Mark,
    Can you post the complete exceptionand stack trace here ?
    Mark Johnson wrote:
    I have a java application which uses JSSE to communicate with a WebMethods server
    and it works great. However, when I take the same code block and run it under
    Weblogic 5.1 sp11, I receive a bad certificate error. After spending a lot of
    time reading through various postings, I fixed the problem where Weblogic was
    intercepting HTTPsURLConnection, but still have the bad_certificate error.
    My setup is as follows:
    - Keys stored using keytool in keystores outside of Weblogic
    - Service pack 9 is installed (also tested SP10)
    - Code runs fine as an isolated java application, but will not run when called
    from within weblogic.
    - JDK1.3.1_02
    - Modified the weblogic.policy file with the following line:"permission java.net.NetPermission
    "specifyStreamHandler";"
    Source Code:
    System.getProperties().put("java.protocol.handler.pkgs",
    "com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    System.out.println("\n\nHandler = "+System.getProperty("java.protocol.handler.pkgs"));
    URL server = new URL(null, "https://B2bserver.quadrem.com:4443/invoke/wm.tn/receive",
    new com.sun.net.ssl.internal.www.protocol.https.Handler());
    System.out.println("Connecting to : "+server.toExternalForm());
    char[] password = "weblogic".toCharArray();
    SSLContext context = SSLContext.getInstance("SSL");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream("x:/jpkeystore"), password);
    keyManagerFactory.init(keystore, password);
    context.init(keyManagerFactory.getKeyManagers(), null, null);
    HttpsURLConnection conn = (HttpsURLConnection)server.openConnection();
    conn.setDoInput( true );
    conn.setDoOutput( true );
    conn.setAllowUserInteraction(false);
    conn.setUseCaches( false );
    conn.setDefaultUseCaches ( false );
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","text/xml");
    conn.setRequestProperty("Host", remoteHost);
    conn.setRequestProperty("Content-Length", "" + (XML_HEADER.length()+doc.length()));
    DataOutputStream out = new DataOutputStream (conn.getOutputStream());
    out.writeBytes(XML_HEADER);
    out.write(doc.getBytes());
    out.flush();
    out.close();
    All help will be appreciated.
    thanks
    Mark Johnson
    781-993-9212 x375
    [email protected]

  • HttpsURLConnection posts OK but empty response (not in browser though)

    Hi All,
    A very odd problem is happening with our system. We use a HttpsURLConnection to connect SSL to a https://www.securehost.com URL.
    Calling this URL in a web browser or posting a form to it returns some text e.g "The Response".
    We post to this URL over the HttpsURLConnection and get a response 200 back. We can also verify that the remote host received our post by contacting them.
    The issue is that unlike in a browser, we get an empty response....here is some logging...
    cipher suite in use on this connection : SSL_RSA_WITH_RC4_128_MD5
    [2003-02-26 09:26:45,538] DEBUG BookingClient root - doPost: connection.getInputStream()
    [2003-02-26 09:26:45,538] DEBUG BookingClient root - doPost: InputStream has 0 bytes available
    [2003-02-26 09:26:45,542] DEBUG BookingClient root - doPost: response= length=0
    Many thanks

    [2003-02-26 09:26:45,538] DEBUG BookingClient root - doPost: InputStream has 0 bytes available"available"? If you're trying to use InputStream.available(), you're done.
    First, available() always returns 0 for SSL connections. If you're relying in it to tell you how much you need to read to get the complete server response, your app is broken.
    Second, available() is not a reliable way to decide how much data the server is sending. All available() tells you is how much data is currently in the network buffer - it may or may not be all (or any) of the data on its way from the server.
    If you're not relying on available(), of course, then there's some other problem. Can you post the code that's reading the stream for us?
    Grant

Maybe you are looking for

  • My iphone will not allow me to turn on the wi-fi setting

    Question My iphone doesn't allow me to turn on the wi-fi setting. The on button is greyed out and won't turn on . I have tried resetting network settings and restoring phone but nothing is working.Any advice?

  • Aperture 3 processes same 519 images on startup

    Every time I open Aperture 3.2.2 it says "processing" and I open the activity window and see that it is processing 519 images.  It gets through all 519 and then the processing stops...but after I quit Aperture, the next time I open it it goes back to

  • Creating an effect - sort of Star Trek-like tractor beam effect

    I'm trying to come up with a way to make a particle effect that sort of looks like a tractor beam effect from Star Trek. I want a line or thin rectangle to be the particle. The particle itself wouldn't spread out or have any speed itself, but I'd lik

  • Everyone without access to Folders, even in CMC

    Hi, I was configuring Folders Top-Level-Security for group Everyone, and I got an java excetion error during the process. Now, when I log on CMC, I can't see the "Folders" options to manage security to Folders, and everyone (all other users) is wihou

  • MouseClicked firing multiple times

    Greetings, I have a GUI Java application with a few buttons that do different things. Sometimes, my mouseClicked event seems to get fired several times instead of the once I've actually clicked it. Example: BTN_Launch.setText("Upload File(s)"); BTN_L