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

By: Ramlak Emailed: 1766 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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.*;

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(17)


1. View Comment

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

View Tutorial          By: Gianni at 2009-05-06 10:02:14
2. View Comment

Thanks a lot. It solved my problem in a second.

View Tutorial          By: Suddy at 2010-03-25 14:56:10
3. View Comment

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.


View Tutorial          By: barani at 2010-05-27 05:32:11
4. View Comment

Would u please provide me with a solution about how to implement a TrustManager or its equivalent class in j2me. Is it really possible to implement a TrustManager for j2me like the one in j2se/j2ee? Please provide me a solution as I am stuck with this for quite a few days.

View Tutorial          By: milan at 2011-02-17 05:39:38
5. View Comment

can you provide the full class from start to begin !

View Tutorial          By: mohit at 2011-12-01 09:56:22
6. View Comment

Thanks lot.Its working good...... thanks lot lot...

View Tutorial          By: Mohanraj at 2011-12-07 05:23:26
7. View Comment

I tried this with HttpUnit (using the custom HostnameVerifier and trustAllSecurityCertificates) and still got the same error. I've tried several articals similar to this one, but "register with the JRE" seems to skip whatever calls HttpUnit is using.
Thank you though!
(When I get this working I'll post my findings both here and at my blog (see URL link), Hacker's Valhalla.


View Tutorial          By: Michael Gower at 2012-01-04 17:40:00
8. View Comment

Thanks a lot for this great post.

View Tutorial          By: Ram Para at 2012-03-23 17:07:09
9. View Comment

Hi,

can we use only code given below :

HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);


and to which function we have to pass the URL??
can u provide sample code?


View Tutorial          By: Mahendra at 2012-05-24 10:57:25
10. View Comment

had the sample problem.. java.io.IOException: HTTPS hostname wrong: should be <server_ip>
Used following code as specified in the post .. & it worked

HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);

Thanks.


View Tutorial          By: java at 2012-08-22 09:39:57
11. View Comment

Thanks for a great post. Solved a problem for me in communicating over SSL with a known server IP. One note: on Android I had to make my custom TrustManager implement X509TrustManager, or I got a "can't find an X509 trust manager" exception when initializing the SSLContext. There might have been some other way around that, but anyway it worked. Thanks again for the post.

View Tutorial          By: Mark at 2013-01-08 07:00:47
12. View Comment

can you plase give an exmple of what should i put in the function when i call here
subscribe(String dist,String userid,String password,String email,String name,String expirydate)


View Tutorial          By: Or at 2013-02-16 11:32:17
13. View Comment

Thanks a lot, a long time I search for solution for this problem. Just a comment, for me dont work "javax.net.ssl.SSLContext.getInstance("SSL");", I used "javax.net.ssl.SSLContext.getInstance("TLS");". :D

View Tutorial          By: Jonhnes at 2013-02-16 17:17:47
14. View Comment

Turning off hostname checking also turns off all security. Yes you are still making an SSL/TLS connection but it could be to evil.com instead of the target server.

Don't do it. If you do it anyhow, just turn off SSL and stop pretending you're secure.


View Tutorial          By: eric at 2014-01-30 18:09:05
15. View Comment

Very good

View Tutorial          By: dizh at 2014-02-21 07:48:19
16. View Comment

Hi it is working fine .but when my server we implemented SSO so each time it is going to login page evnt though i calling to specific url any solutions advaance thanks mohan

View Tutorial          By: mohan at 2014-11-28 10:57:22
17. View Comment

Excellent work mate! works like a charm! Lifesaver!

View Tutorial          By: jmcg at 2015-01-29 02:31:56

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Ramlak
While Loop in VB.net
For Each…Next Loop in VB.net
For Loop in VB.net
Do Loop in VB.net
Setting Up SSL on Tomcat
Unicode and UTF-8 in C
Sample program to demonstrate the use of ActionListener
java.io.IOException: HTTPS hostname wrong: should be
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
NotifyUtil::java.net.ConnectException: Connection refused: connect
'LINK.EXE' is not recognized as an internal or ext
Using Transactions in JDBC
What is the ACID principal?
How connection pooling works in Java and JDBC
A simple JDBC application sample code

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
A Serialization Example in Java
Type Casting in Java
instanceof sample program in Java
Using One-Dimensional Arrays in Java
Method Overriding in Java
indexOf( ) and lastIndexOf( ) in Java
The java Buzzwords
Write to a file in Java - Sample Program
XML and Java - Parsing XML using Java Tutorial
Student marks calculation program in Java
Handling Fractions in Java
Calculate average sale of the week in Java
Java program to check if user input is an even number
HTTPS Java - URL Connection program. Using HttpsURLConnection
LinkedList in Java
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet