我们有一个可以集成在Android应用程序中的sdk。 sdk发出一些HTTP / HTTPS GET请求。 这是执行此操作的代码。
public boolean sendDataToServer(String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
int responseCode = conn.getResponseCode();
if(responseCode != 200) {
String responseBody = getAndClose(conn.getErrorStream());
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
private String getAndClose(InputStream stream) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line).append('\n');
}
return content.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
然而,对于一个应用程序,它在尝试使用HTTPS
进行连接时会出现以下错误IOExcetion while sending the data to server javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x650ed348: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x5e84cf1c:0x00000000)
在同一设备中,如果我使用sdk安装另一个应用程序并发出相同的GET请求,它可以正常工作,我得到200 OK响应。
为什么会发生这种情况以及如何防止这种情况发生?
答案 0 :(得分:0)
使用HttpUrlConnection.setDefaultSSLSocketFactory()方法。
final TrustManager[] certs = new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
@Override
public void checkServerTrusted(final X509Certificate[] chain,
final String authType) {
}
@Override
public void checkClientTrusted(final X509Certificate[] chain,
final String authType) {
}
}};
SSLContext ctx = null;
ctx = SSLContext.getInstance("TLS");
ctx.init(null, certs, new SecureRandom());
HttpUrlConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory();