先来看一段http的请求:
URL url = new URL(serverUrl);
HttpURLConnection conn = url.openConnection()
conn.conect();
//获取文件大小
int length = conn.getContentLength();
//获取输入流
InputStream is = conn.getInputStream();
//do something, such as write2File or write2String
private File write2File(InputStream is){
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file)
//缓存数据
byte buf[] = new byte[1024];
int len = 0;
while((len = is.read(buf)) != -1){
fos.write(buf,0,len)
}
fos.close();
is.close();
}
private String write2String(InputStream is){
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
String str = sb.toString();
fos.close();
is.close();
return str;
}
http改成https,只要将,HttpURLConnection
换成 HttpsURLConnection
即可。
当然一般https都需要证书。只要调用setSSLSocketFactory
设置一个SSLSocketFactory
就可以了。
conn.setSSLSocketFactory(ssContext.getSocketFactory());
如何通过证书封装SSLContext?
private SSLContext getSSLContext (){
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
//privatekey.crt证书文件,将它放在Assets目录下
InputStream is = mContext.getAssets().open("privatekey.crt");
Certificate ca = cf.generateCertificate(is);
Log.i("getSSLContext ", "ca=" + ((X509Certificate) ca).getSubjectDN());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null,null);
keyStore.setCertificateEntry("ca",ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ssContext = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
ssContext.init(null,tmf.getTrustManagers(),null);
return ssContext;
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
修改发起连接处:
URL url = new URL(serverUrl);
//将HttpURLConnection 替换成HttpsURLConnection
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//获取SSLContext
SSLContext ssContext = getSSLContext ();
// 设置setSSLSocketFactory
conn.setSSLSocketFactory(ssContext.getSocketFactory());
conn.conect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
....
其他的就更http的一样了。