【发布时间】:2011-09-27 18:53:24
【问题描述】:
我有一个场景,我必须将证书传递给我的服务器,然后服务器将他的证书发送给我,我必须接受该证书才能访问服务器。我为此使用了 HttpURLConnection,没有任何问题。
但是,我最近遇到了 HttpURLConnection 的问题。我使用的代码从 HTTPS 服务器检索图像。如果图像很小(
javax.net.ssl.SSLProtocolException: 读取错误: ssl=0x3c97e8: SSL 库失败,通常是协议错误
我在网上读到过,很多人说用 HttpClient 代替 HttpURLConnection 是要走的路(一个例子是这个网站http://soan.tistory.com/62 ,认为是用韩文写的,我看不懂但我认为它是这么说的)。
这是我的旧代码,使用 URLConnection:
public static URLConnection CreateFromP12(String uri, String keyFilePath,
String keyPass, TrustManager[] trustPolicy, HostnameVerifier hv) {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
keyStore.load(new FileInputStream(keyFilePath),
keyPass.toCharArray());
kmf.init(keyStore, keyPass.toCharArray());
sslContext.init(kmf.getKeyManagers(), trustPolicy, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception ex) {
return null;
}
URL url;
URLConnection conn;
try {
url = new URL(uri);
conn = url.openConnection();
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
return conn;
}
这是新的,使用 HttpClient:
public class HttpC2Connection {
public static HttpEntity CreateHttpEntityFromP12(String uri,
String keyFilePath, String keyPass) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(keyFilePath), keyPass.toCharArray());
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
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("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
registry);
HttpClient httpclient = new DefaultHttpClient(ccm, params);
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
return entity;
}
但是现在,使用 HttpClient,我的服务器返回一个错误,说我必须通过证书,所以我猜
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
没有加载我的证书。
那么,我怎样才能同时做以下两件事:
1.) 将证书传递给我的服务器; 2.) 接受来自我的服务器的任何证书
使用 HttpClient 类?
PS:我使用的是 Android 3.0
谢谢
【问题讨论】:
标签: java android ssl certificate httpclient