最近苹果宣布所有上架应用都要用https,我们后端走的是同一个函数,导致Android也要连接https.
百度了下,网上说客户端不需要做什么特殊处理,因为cocos本身是支持https的.但是服务端自建的证书是不行的.需要购买的证书才可以.
但是还有个问题,购买的证书,Android可以拿到服务器列表,但是热更新时连不上热更新的服务器.
下面是我的解决方法.(思路是绕过https验证,借鉴了网上的代码)
找到这个jar文件,这个是热更新时连接服务器的java文件编译后的文件.具体的路径在
cocos2d-x-3.13.1\cocos\platform\android\java\src\org\cocos2dx\lib
找到扩展名为.java的文件才能编辑,否则是编辑不了.
下面是我修改的代码部分.
//內建类,下面会用到
public class SSLSocketFactor extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactor(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
// TODO Auto-generated constructor stub
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
}
//修改cocos2dx原有的方法
public static Cocos2dxDownloader createDownloader(int id, int timeoutInSeconds, String tempFileNameSufix, int countOfMaxProcessingTasks) {
Cocos2dxDownloader downloader = new Cocos2dxDownloader();
downloader._id = id; downloader._httpClient.setEnableRedirects(true);
if (timeoutInSeconds > 0) {
downloader._httpClient.setTimeout(timeoutInSeconds * 1000);
} try {
//Secure Protocol implementation.
SSLContext ctx = SSLContext.getInstance("SSL");
//Implementation of a trust manager for X509 certificates
X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx); //允许所有的验证通过
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
downloader._httpClient.setSSLSocketFactory(ssf);
} catch (Exception e) {
e.printStackTrace();
} // downloader._httpClient.setMaxRetriesAndTimeout(3, timeoutInSeconds * 1000);
downloader._httpClient.allowRetryExceptionClass(javax.net.ssl.SSLException.class);
downloader._tempFileNameSufix = tempFileNameSufix;
downloader._countOfMaxProcessingTasks = countOfMaxProcessingTasks;
return downloader;
}