在android2.1如何实现对ssl的无证书访问?(转)

在网上看了,httpchlent的资料,httpchlent4.1可以实现对ssl的无证书访问。

实现代码为:

SSLContextsslcontext=SSLContext.getInstance("TLS");

sslcontext.init(null,newTrustManager[]{easyTrustManager},null);

SSLSocketFactorysf=newSSLSocketFactory(sslcontext);

Schemesch=newScheme("https",sf,8443);

httpclient.getConnectionManager().getSchemeRegistry().register(sch);

但在android2.1中,SSLSocketFactory类中没有下面这个构造函数

SSLSocketFactorysf=newSSLSocketFactory(sslcontext);

客户端不想存放安全证书,请问在android2.1如何实现对ssl的无证书访问?

解决方法如下:

publicStringconnentUrl(StringstrUrl){

StringBuffersbResult=null;

try{

HttpURLConnectionhttp=null;

URLurl=newURL(strUrl);

//判断是http请求还是https请求

if(url.getProtocol().toLowerCase().equals("https")){

trustAllHosts();

HttpsURLConnectionhttps=(HttpsURLConnection)url.openConnection();

https.setHostnameVerifier(DO_NOT_VERIFY);

http=https;

}else{

http=(HttpURLConnection)url.openConnection();

}

http.setDoInput(true);

//设置超时时间

http.setConnectTimeout(10000);

//设置请求类型为post

http.setRequestMethod("POST");

//设置接收类型

http.setRequestProperty("accept","*

privatestaticvoidtrustAllHosts(){

//Createatrustmanagerthatdoesnotvalidatecertificatechains

//Android采用X509的证书信息机制

TrustManager[]trustAllCerts=newTrustManager[]{newX509TrustManager(){

publicjava.security.cert.X509Certificate[]getAcceptedIssuers(){

returnnewjava.security.cert.X509Certificate[]{};

}

publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{}

publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{}

}

};

//Installtheall-trustingtrustmanager

try{

SSLContextsc=SSLContext.getInstance("TLS");

sc.init(null,trustAllCerts,newjava.security.SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

}catch(Exceptione){

e.printStackTrace();

}

}

相关推荐