我有一个Android应用程序,它向服务器发送一个http请求,并从中接收响应。直到今天,我都以这种方式向服务器发送请求:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(http_url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
其中http_url包含我需要调用的脚本的http url(http://www.mydomain.it/script.php)。 现在我已经在我的服务器上购买并安装了SSL证书,因此我需要开始将其用于加密数据。
我使用了相同的代码来发送和接收数据,但我没有使用http_url而是使用了https_url(https://www.mydomain.it/script.php)。 使用wireshark,我注意到数据包已加密,但我知道这是否是发送https请求的正确方法。 DefaultHttpClient是否为开始加密通信提供了所有操作,还是有其他Java类可以做到这一点?
答案 0 :(得分:0)
将此方法用于https请求以获取httpClient:
public DefaultHttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
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);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}