我正在编写一个必须通过 HTTPS 连接到服务器的 Android 应用程序。我尝试的第一个解决方案是这个:(不要介意安全漏洞)
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
Log.d("USR_SSL", e.getMessage());
}
}
//...
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
//This is an HTTPS url
String jsonStr = "";
if(params.length > 1) {
jsonStr = params[1];
}
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
trustAllHosts();
urlConn.setHostnameVerifier(DO_NOT_VERIFY);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
OutputStream os = urlConn.getOutputStream();
os.write(jsonStr.getBytes());
os.flush();
//...
一切都很好(几乎),直到我意识到我还必须使用身份验证、会话和所有这些好东西。使用它应该真的很好:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
但不幸的是我们必须支持Android API level 8,这意味着上面两行代码将不起作用。鉴于此,我已经在 Internet 上搜索了几个小时,试图使用 Apache 类构建解决方案,这些类似乎同时支持 HTTPS 和 Cookie。
这是我设法缝合在一起的代码:
public class ConnectionMediator {
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
public void tryConnect(String url, String data) {
try {
//SSL Stuff
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
//Cookie stuff
HttpContext localContext = new BasicHttpContext();
HttpResponse response = null;
HttpPost httpPost = null;
StringEntity tmp = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
tmp = new StringEntity(data,"UTF-8");
httpPost.setEntity(tmp);
response = httpClient.execute(httpPost,localContext);
} catch(Exception e) {
Log.d("USR_DEBUG", e.getClass().toString() + ": " + e.getMessage());
}
}
}
在写这篇文章的时候,我得到了一个NetworkOnMainThreadException
,但这并不重要;重要的是我想指出的是,我不知道自己在做什么,例如,通过 HTTPS 简单地连接并使用 cookie,必须使用 13 个我从未听说过的不同类的。显然,我对 HTTPS/Java 网络类的了解几乎为零,但尽管如此,我还是希望得到更直观的东西。因此,我的问题不是“这不起作用”类型的问题,而是“我应该做什么”,甚至是“我如何学习我必须做的事情?”。
非常感谢,
一个非常困惑的编码器