我的defaultHttpClient
存在问题。
我必须连接到使用HTTPS连接的服务器。我发现HttpClient
默认使用TLS
安全协议和我想要连接的服务器不支持它。
我无法改变这一点,我不得不在我的应用程序中更改我的安全协议!
我该怎么做?
答案 0 :(得分:0)
尝试这个客户端,它帮了我很多次。
public class MyHttpClient1 extends DefaultHttpClient {
final Context context;
MyHttpClient1 mHttpClient=null;
public MyHttpClient1(Context context) {
this.context = context;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
KeyStore trustStore = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
trustStore.load(null, null);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
try {
registry.register(new Scheme("https",new MySSLSocketFactory(trustStore), 443));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
return new SingleClientConnManager(getParams(), registry);
}
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("SSL"); //or TLS
public MySSLSocketFactory(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();
}
}
答案 1 :(得分:0)
这似乎不起作用,但我通过添加方法解决了它:
setEnableProtocols(new String[]{"SSLv3"});
创建我的个人SSLSocket
现在一切似乎都有效了!