Android Https使用

http://blog.sina.com.cn/s/blog_7573977301017xto.html

直接上代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException ;
import java.security.UnrecoverableKeyExceptio n;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class HttpsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
new Thread(new Runnable() {

public void run() {
Log.e("xx", "start");
sendrequest();
installCert("10.167.17.187", 8443, "changeit", "TLS");
sendrequest();
Log.e("xx", "end");
}
}).start();
}

private HttpPost makeHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
HttpParams timeParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(timeParams, 30 * 1000);
HttpConnectionParams.setSoTimeout(timeParams, 30 * 1000);
httpPost.setParams(timeParams);
return httpPost;
}

private HttpClient makeHttpsClient(String keyStorePasswd, int port) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
String trustStorePath = System
.getProperty("javax.net.ssl.trustStore");
// File keystoreFile = new File(trustStorePath);
// 由于android权限原因,无法读取trustStorePath="//system/etc/security/cacerts.bks"文件,此处由sdcard代替
File keystoreFile = new File("/sdcard/cacerts.bks");
trustStore.load(new FileInputStream(keystoreFile), keyStorePasswd
.toCharArray());
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
socketFactory.setHostnameVerifier(new X509HostnameVerifier() {
public boolean verify(String host, SSLSession session) {
return true;
}

public void verify(String host, SSLSocket ssl)
throws IOException {
}

public void verify(String host, X509Certificate cert)
throws SSLException {
}

public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
});
Scheme sch = new Scheme("https", socketFactory, port);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
return httpClient;
} catch (KeyStoreException e) {
Log.e("xx", e.getMessage());
} catch (NoSuchAlgorithmException  e) {
Log.e("xx", e.getMessage());
} catch (CertificateException e) {
Log.e("xx", e.getMessage());
} catch (KeyManagementException e) {
Log.e("xx", e.getMessage());
} catch (UnrecoverableKeyExceptio n e) {
Log.e("xx", e.getMessage());
} catch (IOException e) {
Log.e("xx", e.getMessage());
}
return null;
}

private void sendrequest() {
try {
HttpClient httpClient = makeHttpsClient("changeit", 8443);
HttpPost httpPost = makeHttpPost("https://10.167.17.187:8443");
HttpResponse response;
response = httpClient.execute(httpPost);

if (response != null) {
Log.i("xx", "" + response.getStatusLine().getStatusCode());
} else {
Log.i("xx", "NULL");
}
} catch (ClientProtocolException e) {
Log.e("xx", e.getMessage());
} catch (IOException e) {
Log.e("xx", e.getMessage());
}
}

private static void installCert(String host, int port, String passwd,
String sslProtocol) {
try {
String trustStorePath = System
.getProperty("javax.net.ssl.trustStore");
// File keystoreFile = new File(trustStorePath);
// 由于android权限原因,无法读取trustStorePath="//system/etc/security/cacerts.bks"文件,此处由sdcard代替
File keystoreFile = new File("/sdcard/cacerts.bks");
InputStream in = new FileInputStream(keystoreFile);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passwd.toCharArray());
in.close();

SSLContext context = SSLContext.getInstance(sslProtocol);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);

X509TrustManager defaultTrustManager = (X509TrustManager) tmf
.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
javax.net.ssl.SSLSocketFactory factory = context.getSocketFactory();
boolean istrusted = false;
try {
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(50000);
socket.startHandshake();
socket.close();
istrusted = true;
} catch (SSLException e) {
Log.i("xx", e.getMessage());
istrusted = false;
}
if (!istrusted) {
X509Certificate[] chain = tm.chain;
if (chain == null) {
return;
}
ks.setCertificateEntry(host + "_" + 0, chain[0]);
// 如果想更改新密码,这个passwd替换成新密码即可
ks.store(new FileOutputStream(new File("/sdcard/cacerts.bks")),
passwd.toCharArray());
}

} catch (FileNotFoundException e) {
Log.e("xx", e.getMessage());
} catch (NoSuchAlgorithmException  e) {
Log.e("xx", e.getMessage());
} catch (CertificateException e) {
Log.e("xx", e.getMessage());
} catch (IOException e) {
Log.e("xx", e.getMessage());
} catch (KeyStoreException e) {
Log.e("xx", e.getMessage());
} catch (KeyManagementException e) {
Log.e("xx", e.getMessage());
}
}

private static class SavingTrustManager implements X509TrustManager {

private final X509TrustManager tm;
private X509Certificate[] chain;

SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}

public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationExce ption();
}

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationExce ption();
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值