java.io.IOException: HTTPS hostname wrong: should be

By Ramlak Viewed: 31796 times Emailed: 212 times Printed: 242 times Bookmark and Share



java.io.IOException: HTTPS hostname wrong: should be

This error occurs when you are trying to access a HTTPS url. You might have already installed the server certificate to your JRE's keystore. But this error means that the name of the server certificate does not match with the actual domain name of the server that is mentioned in the URL. This normally happens when you are using a non CA issued certificate.

But of course you can overcome this problem by instructing the JRE to trust all certificates and to ignore the mis match in the domain name and the certificate issuer. Here is the snippet of code that can be used to achieve this.

This is not the complete class. But I have provided the complete code that is functional. You just have to copy the entire code below add it to any of your class and then call the subscribe function from anywhere you want. 

public String subscribe(String dist,String userid,String password,
	String email,String name,String expirydate) throws Exception{
        String resp = "";
        String urlString="https://<secureserver>/";
        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;
        String str = "";
        int flag=1;
        
        try {
            Properties sysProperties = System.getProperties();
	   // change proxy settings if required and enable the below lines
           // sysProperties.put("proxyHost", "proxy.starhub.net.sg");
           // sysProperties.put("proxyPort", "8080");
           // sysProperties.put("proxySet",  "true");
// Now you are telling the JRE to ignore the hostname
               HostnameVerifier hv = new HostnameVerifier()
    {
        public boolean verify(String urlHostName, SSLSession session)
        {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                    + session.getPeerHost());
            return true;
        }
    };
           // Now you are telling the JRE to trust any https server. 
           // If you know the URL that you are connecting to then this should not be a problem
            trustAllHttpsCertificates();
             HttpsURLConnection.setDefaultHostnameVerifier(hv);
    
            url = new URL(urlString);
            urlConn = url.openConnection();
            urlConn.setDoInput(true);
            Object object;
            urlConn.setUseCaches(false);
            
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            input = new DataInputStream(urlConn.getInputStream());
            
            while (null != ((str = input.readLine()))){
                if (str.length() >0){
                    str = str.trim();
                    if(!str.equals("")){
                        //System.out.println(str);
                        resp += str;
                    }
                }
            }
            input.close();
        }catch(MalformedURLException mue){ mue.printStackTrace();}
        catch(IOException ioe){ ioe.printStackTrace();}
        
        return resp;
    }
// Just add these two functions in your program 
    public static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager
    {
        public java.security.cert.X509Certificate[] getAcceptedIssuers()
        {
            return null;
        }
 
        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs)
        {
            return true;
        }
 
        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs)
        {
            return true;
        }
 
        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException
        {
            return;
        }
 
        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException
        {
            return;
        }
    }

 
    private static void trustAllHttpsCertificates() throws Exception
    {
 
        //  Create a trust manager that does not validate certificate chains:
 
        javax.net.ssl.TrustManager[] trustAllCerts =
 
        new javax.net.ssl.TrustManager[1];
 
        javax.net.ssl.TrustManager tm = new miTM();
 
        trustAllCerts[0] = tm;
 
        javax.net.ssl.SSLContext sc =
 
        javax.net.ssl.SSLContext.getInstance("SSL");
 
        sc.init(null, trustAllCerts, null);
 
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
 
        sc.getSocketFactory());
 
    }

 If you are not able to compile it is probably due to import issues. 
So see if these are imported in your class.
import java.security.Security;
import java.security.Provider;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.*;



Comments(3)


1. Many thanks. I had that problem and your code solved it perfectly.

By: Gianni at 2009-05-06 10:02:14
2. Thanks a lot. It solved my problem in a second.

By: Suddy at 2010-03-25 14:56:10
3. hi ,
i tried the code given, the connection itself not established it throws connetion timed out error and ssl hand shanking.please can you explain the cause of those errors.


By: barani at 2010-05-27 05:32:11

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-09-02]Steps in using verisign certificate with Glassfish appserver
[2010-08-02]emulator 0 terminated while waiting for it to register!
[2010-08-02]Cannot run program "C:\Program Files\Java\jre6\bin\javac.exe": CreateProcess error=2, The system cannot find the file specified
[2010-08-01]Step by Step guide to setup freetts for Java
[2010-07-31]Speech Packages available for Java API
[2010-07-31]Tutorial on setting up freetts with maven
[2010-07-31]package com.sun.speech.freetts does not exist.
[2010-07-31]Text to Speech conversion program in Java
[2010-07-31]How to create wav file using freetts
[2010-07-31]How to set the width of a Text element in JavaFX?
[2010-07-31]Major components of FxObjects in JavaFX
[2010-07-03]Using the AWS SDK for Java in Eclipse
[2010-07-03]Using the AWS SDK for Java
[2010-01-01]Converting properties using PropertyEditors and Other Spring features worth mentioning
[2010-01-01]How to create an array and method in JSP

More Latest News

Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
XML and Java - Parsing XML using Java Tutorial
How to use Iterator in Java
How to Send SMS using Java Program (full code sample included)
Using substring( ) in Java
indexOf( ) and lastIndexOf( ) in Java
FileReader and FileWriter example program in Java
Using StringTokenizer in Java
HashMap example in Java
wait(), notify() and notifyAll() in Java - A tutorial
Method Overloading (function overloading) in Java
Abstract classes in Java
Method Overriding in Java
Transient vs Volatile modifiers in Java
compareTo( ) in Java
Most Emailed Articles (in last 30 days)
Components of program
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Why java is important to the Internet
How to use ArrayList in Java
Execute system commands in a Java Program
FileReader and FileWriter example program in Java
Recursion in java
indexOf( ) and lastIndexOf( ) in Java
What is Java?
Method Overloading (function overloading) in Java
Sample Java Script that displays a movable clock
compareTo( ) in Java
History of Object
How to use Iterator in Java