httpurl下载
File descFile = new File(MainActivity.this.getCacheDir(), fileName);
// Android 4.0 之后不能在主线程中请求HTTP请求
if (downflag){
download(descFile);
}
new Thread(new Runnable(){
@Override
public void run() {
try {
HttpURLConnection conn = null;
trustAllHosts();
URL httpUrl = new URL(url);
HttpsURLConnection https = (HttpsURLConnection)httpUrl.openConnection();
if (httpUrl.getProtocol().toLowerCase().equals("https")) {
https.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn = https;
} else {
conn = (HttpURLConnection)httpUrl.openConnection();
}
conn.setRequestProperty("Cookie",cookieStr);
conn.setRequestProperty("Host","mail.ejianlong.com");
// 设置连接主机超时时间
conn.setConnectTimeout(5 * 1000);
//设置从主机读取数据超时
conn.setReadTimeout(5 * 1000);
// 设置是否使用缓存 默认是true
conn.setUseCaches(true);
// 设置为Post请求
conn.setRequestMethod("GET");
// conn.connect();
// 判断请求是否成功
if (conn.getResponseCode() == 200) {
FileOutputStream fos = new FileOutputStream(descFile);;
byte[] buffer = new byte[1024];
int len;
InputStream inputStream = conn.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
// 写到本地
fos.write(buffer, 0, len);
}
Log.e("文件下载完成", "文件下载完成");
// Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
downflag = true;
handlerIntent.setDataAndType(uri, mimeType);
// // 以下固定写法
// final Intent intent = new Intent(Intent.ACTION_VIEW,
// uri);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// startActivity(intent);
startActivity(handlerIntent);
} else {
Log.e("文件下载失败", "文件下载失败");
}
// 关闭连接
conn.disconnect();
} catch (Exception e) {
Log.e("文件下载失败", e.toString());
}
}
private void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkServerTrusted");
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
还没有评论,来说两句吧...