HttpURLConnection中econnreset异常之后的理解

/*** 文件下载 */
	class downloadTask extends Thread {
		private String downloadUrl;// 下载链接地址
		private String filePath;// 保存文件路径地址
		private int position; //确定下载列表中的索引号
	
		public downloadTask(String downloadUrl, String fileptah,int position) {
			this.downloadUrl = downloadUrl;
			this.filePath = fileptah;
			this.position = position;
		}
		@Override
		public void run() {
			try {
				URL url = new URL(downloadUrl);
				//LogHelper.e(TAG,  "download file http path:" + position +" | " + downloadUrl);
				LogHelper.e("线程", this.hashCode() + "|" + downloadUrl);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setConnectTimeout(40*1000) ; 
				conn.setRequestProperty("Charset", "UTF-8");  
			    //设置为长连接  
		        conn.setRequestProperty("Connection", "Keep-Alive");  
				conn.setAllowUserInteraction(true);
				conn.setReadTimeout(40*1000);
				// 读取下载文件总大小
				int fileSize = conn.getContentLength();
				if (fileSize <= 0) {
					System.out.println("读取文件失败");
					return;
				}
				// 设置ProgressBar最大的长度为文件Size
				holderList.get(position).PBDOWNLOAD.setMax(fileSize);
				synchronized(this){
				BufferedInputStream bis = null;
				byte[] buffer = new byte[1024];
				bis = new BufferedInputStream(conn.getInputStream());
				LogHelper.e("线程", this.hashCode() + "|" +bis.hashCode() );
				FileOutputStream fos  =  new  FileOutputStream(filePath, true);	
				/** 当前下载文件长度 */
				
				int downloadLength = 0;
				int len;
				while ((len = bis.read(buffer, 0, 1024)) != -1) {
					fos.write(buffer, 0, len);
					downloadLength += len;
					// 通知handler去更新视图组件
					Message msg = new Message();
					msg.getData().putInt("size", downloadLength);
					msg.getData().putInt("position", position);
					
					downloadHandler.sendMessage(msg);
					}	
				
				//关闭文件IO连接
				if(fos != null){
					fos.close();
				}
				//关闭网络流
				if(bis != null){
					bis.close();
				}
				//关闭http连接
				if(conn != null){
					conn.disconnect();
				}
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
				LogHelper.e("aaaaaaaa", e.getMessage());
			} 

		}
	}




注意事项:

1、关闭连接和流 

2、conn.setReadTimeout(40*1000);  当网速不好,或者多个线程抢占cpu,导致下载文件在一定时间里没有执行下载操作,服务器以为客户端已经断开连接,服务器会关闭连接,导致程序下载出错。因此考虑到特殊情况,可以适当的把conn.setReadTimeout(40*1000)设置长一点。

conn.setReadTimeout(40*1000);
conn.setReadTimeout(40*1000);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值