HTTPS和自签名证书问题 [英] HTTPS and self-signed certificate issue
问题描述
我必须使用HTTP POST发送请求到服务器(使用自签名证书)。这就是我如何做到这一点:
I have to use HTTPS for sending POST requests to a server (using a self-signed certificate). This is how I do it:
HttpClient httpClient = getHttpClient();
for (int i = 0; i < PARAMS.length && !mHttpPost.isAborted(); ++i) {
mHttpPost.setURI(URI.create(mUri + "/" + PARAMS[i].getPath()));
mHttpPost.setEntity(new UrlEncodedFormEntity(PARAMS[i].getContents(), HTTP.UTF_8));
HttpResponse response = httpClient.execute(mHttpPost);
[...]
}
使用getHttpClient()定义如下:
With getHttpClient() defined as follows:
public static DefaultHttpClient getHttpClient() {
DefaultHttpClient client = null;
// Setting up parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
// Setting timeout
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
HttpConnectionParams.setSoTimeout(params, TIMEOUT);
// Registering schemes for both HTTP and HTTPS
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", sslSocketFactory, 443));
// Creating thread safe client connection manager
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
// Creating HTTP client
client = new DefaultHttpClient(manager, params);
return client;
}
不过,我得到一个不受信任的服务器证书异常。我知道自签名证书的一些问题已经张贴在这里,但他们没有工作对我来说...
But I get a "Not trusted server certificate" exception. I know several questions about self-signed certificates have already been posted here, but none of them worked for me...
有谁知道该怎么办?
一些细节:我正在与仿真器API级别4(安卓1.6)
Some details: I'm working with API level 4 (Android 1.6) on emulator.
推荐答案
我终于解开了它,使用的SSLSocketFactory的自定义子类:
I finally solved it, using a custom subclass of SSLSocketFactory:
public class CustomSSLSocketFactory extends SSLSocketFactory {
private SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
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);
}
@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 HttpClient getHttpClient() {
DefaultHttpClient client = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// Setting up parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
// Setting timeout
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
HttpConnectionParams.setSoTimeout(params, TIMEOUT);
// Registering schemes for both HTTP and HTTPS
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
// Creating thread safe client connection manager
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
// Creating HTTP client
client = new DefaultHttpClient(ccm, params);
// Registering user name and password for authentication
client.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials(mUsername, mPassword));
} catch (Exception e) {
client = new DefaultHttpClient();
}
return client;
}
不知道为什么其他的解决方案,我发现我没有工作......
Don't know why the other solutions I found did not work for me...
这篇关于HTTPS和自签名证书问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!