现在很多网站的请求都需要使用HTTPS验证,查看google官方的HTTPS请求中可以
发现很蛋疼的会有一个keystore对象,也就是要一个证书(CA),但是如果你没有一
个有效的SSL certificate,你可能想让你的APP去忽略certificate的验证,这里将列出
两种情况下的做法:
1、HTTPSConnection
我们都知道在发送http请求时用的是HTTPConnection,但是发送https请求时使用的是
HTTPSConnection,下面看一下具体做法
首先是创建一个方法来初始化
private static void initTrustSSL() {
try {
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
// do nothing, let the check pass.
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
然后在使用前先调用该方法
URL mURL = new URL("https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=sjrand");
initTrustAllSSL();
HttpsURLConnection mConnection = (HttpsURLConnection) mURL.openConnection();
2、httpclient
在使用封装好httpclient中需要注册https,http,如下所示
private static HttpClient createHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
return new DefaultHttpClient(conMgr, params);
}
然后是使用方法,和普通的http请求一样
public static String sendData(String url, List<NameValuePair> datas) {
HttpClient client = createHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse resp = null;
String result = "";
try {
post.setEntity(new UrlEncodedFormEntity(datas, HTTP.UTF_8));
resp = client.execute(post);
result = EntityUtils.toString(resp.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}