最近有因为找工作去一些知名互联网公司面试,被问到好多Android基础,但是本人基础,渣渣。失败后决定要恶补自己的不足。
所以开了博客,从头开始。
总在CSDN上看张兴业的博客,很感谢。特此声明、
转载:http://blog.csdn.net/xyz_lmn/article/details/8803357
上面详细记载了,Https 的两种使用情况。
android中实现Https基本就这两种方式,一种是不验证证书,一种是有验证证书(预防钓鱼)。
本人很同意,首先不管我们是否采用Https进行防钓鱼的协议连接服务器,都要看用户是否主动去下载哪些非正规的app或者链接。
但是身为程序员,我们能做的就是尽自己的可能,完善安全机制。
现在我们来看看第一种的实现方式:(不验证证书)。
因为很多时候我们的https的服务器所使用的根证书,都是自签的,或者签名机构不在我们httpclient工具类的信任列表之中(也就是白名单),所以办法就只有两个,要不就是我们把服务器的根证书添加到httpclient的信任列表中,要不就是让httpclient信任所有的证书。
添加好信任列表很麻烦,而且出错率很高,所有在很多需要的场景下,采用后者,让httpclient信任所有证书。但是简单的同时,安全性肯定会下降的。鱼和熊掌不可兼得麽。
<span style="font-size:14px;">直接给代码:</span>
<span style="font-size:14px;">public class HttpsTestActivity extends Activity {
/** Called when the activity is first created. */
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.textView1);
GetHttps();
}
private void GetHttps(){
String https = "https://www.google.com.hk";//服务器指定的url地址
try{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection)new URL(https).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
text.setText(sb.toString());
}catch(Exception e){
Log.e(this.getClass().getName(), e.getMessage());
}
}
private class MyHostnameVerifier implements HostnameVerifier{
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
}
</span><span style="font-size:10px;">//</span><span style="color: rgb(51, 51, 51); font-family: Verdana, Arial, Helvetica, sans-serif; line-height: 24px;"><span style="font-size:10px;">另外使用HttpsURLConnection时需要实现HostnameVerifier 和 X509TrustManager,这两个实现是必须的,要不会报安全验证异常。然后初始化X509TrustManager中的SSLContext,为javax.net.ssl.H//ttpsURLConnection设置默认的SocketFactory和HostnameVerifier。 </span><span style="font-size:14px;"> </span></span><span style="font-size:14px;">
private class MyTrustManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
}</span>
另外有喜欢封装的同学,可以参考http://blog.csdn.net/123bobo/article/details/7264350/
特定绑定服务器的接口。