I am using below code to connect to https://api.twilio.com:8443.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
public class SampleApp {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyManagementException {
URL url = new URL("https://api.twilio.com:8443/");
java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null,null);
SSLContext.setDefault(sslContext);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
When executing the above code with Java 1.7, it gives below exception:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1979)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1086)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1301)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
But when running the same code with Java 1.8, it gives expected output as:
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Versions>
<Versions>
<Version>
<Name>2010-04-01</Name>
<Uri>/2010-04-01</Uri>
<SubresourceUris>
<Accounts>/2010-04-01/Accounts</Accounts>
</SubresourceUris>
</Version>
</Versions>
</Versions>
</TwilioResponse>
I am aware that JDK 8 will use TLS 1.2 as default. So, I have explicitly provided the http protocol in the code itself. Could anyone kindly explain me the reason for above behaviour and also how can I connect through Java 1.7?