While I was testing creating a secure connection to a new REST service am integrating with & despite I made sure I imported their certificate, I was getting the exception below:
java.io.IOException: HTTPS hostname wrong: should be <connect2.bglobale.com>
at com.ibm.net.ssl.www2.protocol.https.c.b(c.java:117)
at com.ibm.net.ssl.www2.protocol.https.c.afterConnect(c.java:138)
at com.ibm.net.ssl.www2.protocol.https.d.connect(d.java:64)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1024)
at com.ibm.net.ssl.www2.protocol.https.b.getOutputStream(b.java:51)
at temporary.test.TestConnection.main(TestConnection.java:36)
After some investigation, I found that a self signed certificate might raise this exception even if it is created with the right domain (connect2.bglobale.com in my case) & the only way around it, is to force Java to fully trust the host-name which be achieved using the "Hostname Verifier" as shown in the example below:
package temporary.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class TestConnection {
public static void main (String args[]){
StringBuffer jsonString=new StringBuffer();
String line;
HostnameVerifier hv = new HostnameVerifier(){
public boolean verify(String urlHostName, SSLSession session){
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
try{
URL url = new URL("https://connect2.bglobale.com/Browsing/AppSettings?merchantGUID=1fccd7e5");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setHostnameVerifier(hv);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
String data = "";
connection.setRequestProperty("Content-Length",""+data.length());
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("" + data);
writer.close();
System.out.println("Response code: "+connection.getResponseCode());
System.out.println("Response message: "+connection.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
System.out.println("JSON String = "+jsonString);
br.close();
connection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}
The code highlighted in red is the one required to fix the problem.
No comments:
Post a Comment