【发布时间】:2012-02-22 01:57:04
【问题描述】:
我需要从与我的 Android 应用程序进行 https 通信的服务器中检索数据。 我像这样动态获取服务器证书:
KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
store.load(null);
URLConnection uc = new URL("https://duckduckgo.com/").openConnection();
uc.connect();
Certificate certs[] = ((HttpsURLConnection) uc).getServerCertificates();
for (int i = 0; i < certs.length; i++) store.setCertificateEntry("cert_"+ i, certs[i]);
((HttpsURLConnection) uc).disconnect();
我有一个自定义的 HttpClient:
public class MyHttpClient extends DefaultHttpClient {
final KeyStore store;
public MyHttpClient(KeyStore store) {
this.store = store;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
return new SSLSocketFactory(store);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
并像这样从服务器检索数据:
HttpEntity responseEntity;
URI url = new URI("https://duckduckgo.com/?q=android+java");
HttpGet httpGet = new HttpGet(url );
HttpClient client = new MyHttpClient(store);
httpGet.addHeader("Content-Type", "text/xml");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse getResponse = client.execute(httpGet);
我发送和接收的所有内容都加密了吗?
我在想也许我必须向服务器提供我的公钥?
【问题讨论】:
-
没有“私人证书”之类的东西。获取服务器证书并将它们存储到信任库中将不起作用,除非它们已经被信任库信任,即存在于信任库中,这是循环的。不清楚你在问什么。
标签: java android https certificate private