sura2k
sura2k

Reputation: 7517

Cannot call HTTPS untrusted URL from java client

I want to call an https url from java and it is not trusted, and also it has no domain name but ip (public or private). When I call a url which has a domain name with untrusted certificate, it works. But of an IP address it doesn't work. This is the error I got and the source code. Can you tell me what is the problem and a way to solve this.

Thank you!

Error:

java.io.IOException: HTTPS hostname wrong:  should be <xxx.xxx.xxx.xxx>

Source:

public static void main(String args[]){

        StringBuffer param = new StringBuffer();
        param.append("https://xxx.xxx.xxx.xxx/insert.php");
        param.append("?a=a");
        param.append("&b=c");
        param.append("&c=c");   
        System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        try{
            URL url =new URL(param.toString());
            URLConnection con = url.openConnection();
            con.setAllowUserInteraction(true);
            con.getInputStream();
            BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer result = new StringBuffer();

            while ((inputLine = in.readLine()) != null){
                result.append(inputLine);
                            }
            in.close();

            System.out.println("Result=" + result.toString());
        }catch(Exception ee){
            System.out.print(ee);
        }

}

Upvotes: 0

Views: 1354

Answers (1)

Bruno
Bruno

Reputation: 122609

Unlike some browsers, Oracle's Java implementation of the hostname verifier follows RFC 2818 (the HTTPS specification) strictly when IP addresses are used (as opposed to host names). In particular, there MUST be an IP entry in the Subject Alternative Name extension.

More details in this answer.

Note that the code linked from a comment simply disables any certificate verification, which will make it potentially open to Man-In-The-Middle attacks: don't use it!

Upvotes: 1

Related Questions