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);

你可能感兴趣的:(android)