Android/Java -- 如何创建HTTPS连接?
我这里有代码,允许我连接到https服务器并传输数据。它工作得很好,但我想知道我是否以正确的方式做到这一点,我实际上正在建立安全连接。请检查我的工作。谢谢。
public class HTTPSClient extends DefaultHttpClient
{
public HTTPSClient()
{
}
@Override
protected ClientConnectionManager createClientConnectionManager()
{
SchemeRegistry registry = new SchemeRegistry();
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
final SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
//socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", socketFactory, 80));
registry.register(new Scheme("https", socketFactory, 443));
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
return new SingleClientConnManager(params, registry);
}
}
我像这样使用这个代码:
HttpResponse response = mConnection.httpsClient.execute(new HttpHost("www.somehostname.com", 80), new HttpGet("https://someaddress")));
然后我从那里阅读了回复。再次感谢。