Java 服務器端支持斷點續傳的源代碼

Java 服務器端支持斷點續傳的源代碼【支持快車、迅雷】(僅支持 HTTP 協議) 網上關於 Java 支持 HTTP 斷點續傳的文章很多,但關於 Java 服務器端支持 HTTP 斷點續傳的卻比較少。 本文是 Java 服務器端支持 HTTP 斷點續傳的源代碼,支持快車、迅雷。 本文使用一個簡單的 Servlet 來做爲支持斷點續傳的下載示例,在 Java Web 項目下部署好後,可使用諸如 http://localhost/cds/http 的連接來調用 Servlet,進而被快車/迅雷監聽進行下載。 ArcSyncHttpDownloadServlet 源代碼: [java] view plaincopyprint? package com.defonds.cds.common; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.defonds.cds.common.util.CommonUtil; //HTTP 斷點續傳 demo(客戶端測試工具:快車、迅雷) public class ArcSyncHttpDownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; final static Log log = LogFactory.getLog(ArcSyncHttpDownloadServlet.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { File downloadFile = new File("D:/defonds/book/pattern/SteveJobsZH.pdf");//要下載的文件 long fileLength = downloadFile.length();//記錄文件大小 long pastLength = 0;//記錄已下載文件大小 int rangeSwitch = 0;//0:從頭開始的全文下載;1:從某字節開始的下載(bytes=27000-);2:從某字節開始到某字節結束的下載(bytes=27000-39000) long toLength = 0;//記錄客戶端須要下載的字節段的最後一個字節偏移量(好比bytes=27000-39000,則這個值是爲39000) long contentLength = 0;//客戶端請求的字節總量 String rangeBytes = "";//記錄客戶端傳來的形如「bytes=27000-」或者「bytes=27000-39000」的內容 RandomAccessFile raf = null;//負責讀取數據 OutputStream os = null;//寫出數據 OutputStream out = null;//緩衝 byte b[] = new byte[1024];//暫存容器 if (request.getHeader("Range") != null) {// 客戶端請求的下載的文件塊的開始字節 response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); log.info("request.getHeader(\"Range\")=" + request.getHeader("Range")); rangeBytes = request.getHeader("Range").replaceAll("bytes=", ""); if (rangeBytes.indexOf('-') == rangeBytes.length() - 1) {//bytes=969998336- rangeSwitch = 1; rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-')); pastLength = Long.parseLong(rangeBytes.trim()); contentLength = fileLength - pastLength + 1;//客戶端請求的是 969998336 以後的字節 } else {//bytes=1275856879-1275877358 rangeSwitch = 2; String temp0 = rangeBytes.substring(0,rangeBytes.indexOf('-')); String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length()); pastLength = Long.parseLong(temp0.trim());//bytes=1275856879-1275877358,從第 1275856879 個字節開始下載 toLength = Long.parseLong(temp2);//bytes=1275856879-1275877358,到第 1275877358 個字節結束 contentLength = toLength - pastLength + 1;//客戶端請求的是 1275856879-1275877358 之間的字節 } } else {//從開始進行下載 contentLength = fileLength;//客戶端要求全文下載 } /** * 若是設設置了Content-Length,則客戶端會自動進行多線程下載。若是不但願支持多線程,則不要設置這個參數。 * 響應的格式是: * Content-Length: [文件的總大小] - [客戶端請求的下載的文件塊的開始字節] * ServletActionContext.getResponse().setHeader("Content-Length", * new Long(file.length() - p).toString()); */ response.reset();//告訴客戶端容許斷點續傳多線程鏈接下載,響應的格式是:Accept-Ranges: bytes response.setHeader("Accept-Ranges", "bytes");//若是是第一次下,尚未斷點續傳,狀態是默認的 200,無需顯式設置;響應的格式是:HTTP/1.1 200 OK if (pastLength != 0) { //不是從最開始下載, //響應的格式是: //Content-Range: bytes [文件塊的開始字節]-[文件的總大小 - 1]/[文件的總大小] log.info("----------------------------不是從開始進行下載!服務器即將開始斷點續傳..."); switch (rangeSwitch) { case 1 : {//針對 bytes=27000- 的請求 String contentRange = new StringBuffer("bytes ").append(new Long(pastLength).toString()).append("-").append(new Long(fileLength - 1).toString()).append("/").append(new Long(fileLength).toString()).toString(); response.setHeader("Content-Range", contentRange); break; } case 2 : {//針對 bytes=27000-39000 的請求 String contentRange = rangeBytes + "/" + new Long(fileLength).toString(); response.setHeader("Content-Range", contentRange); break; } default : { break; } } } else { //是從開始下載 log.info("----------------------------是從開始進行下載!"); } try { response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFile.getName() + "\""); response.setContentType( CommonUtil.setContentType(downloadFile.getName()));// set the MIME type. response.addHeader("Content-Length", String.valueOf(contentLength)); os = response.getOutputStream(); out = new BufferedOutputStream(os); raf = new RandomAccessFile(downloadFile, "r"); try { switch (rangeSwitch) { case 0 : {//普通下載,或者從頭開始的下載 //同1 } case 1 : {//針對 bytes=27000- 的請求 raf.seek(pastLength);//形如 bytes=969998336- 的客戶端請求,跳過 969998336 個字節 int n = 0; while ((n = raf.read(b, 0, 1024)) != -1) { out.write(b, 0, n); } break; } case 2 : {//針對 bytes=27000-39000 的請求 raf.seek(pastLength - 1);//形如 bytes=1275856879-1275877358 的客戶端請求,找到第 1275856879 個字節 int n = 0; long readLength = 0;//記錄已讀字節數 while (readLength <= contentLength - 1024) {//大部分字節在這裏讀取 n = raf.read(b, 0, 1024); readLength += 1024; out.write(b, 0, n); } if (readLength <= contentLength) {//餘下的不足 1024 個字節在這裏讀取 n = raf.read(b, 0, (int)(contentLength - readLength)); out.write(b, 0, n); } // // raf.seek(pastLength);//形如 bytes=1275856879-1275877358 的客戶端請求,找到第 1275856879 個字節 // while (raf.getFilePointer() < toLength) { // out.write(raf.read()); // } break; } default : { break; } } out.flush(); } catch(IOException ie) { /** * 在寫數據的時候, * 對於 ClientAbortException 之類的異常, * 是由於客戶端取消了下載,而服務器端繼續向瀏覽器寫入數據時, * 拋出這個異常,這個是正常的。 * 尤爲是對於迅雷這種吸血的客戶端軟件, * 明明已經有一個線程在讀取 bytes=1275856879-1275877358, * 若是短期內沒有讀取完畢,迅雷會再啓第二個、第三個。。。線程來讀取相同的字節段, * 直到有一個線程讀取完畢,迅雷會 KILL 掉其餘正在下載同一字節段的線程, * 強行停止字節讀出,形成服務器拋 ClientAbortException。 * 因此,咱們忽略這種異常 */ //ignore } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } if (raf != null) { try { raf.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } } } ArcSyncHttpDownloadServlet 的 web.xml 配置清單: [html] view plaincopyprint? <!-- HTTP 斷點續傳 demo:127.0.0.1/cds/http --> <servlet> <servlet-name>httpServlet</servlet-name> <servlet-class>com.defonds.cds.common.ArcSyncHttpDownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>httpServlet</servlet-name> <url-pattern>/http</url-pattern> </servlet-mapping> ArcSyncHttpDownloadServlet 調用到的工具類 com.defonds.cds.common.util.CommonUtil 源代碼: [java] view plaincopyprint? package com.defonds.cds.common.util; public class CommonUtil { public static String setContentType(String returnFileName){ String contentType = "application/octet-stream"; if (returnFileName.lastIndexOf(".") < 0) return contentType; returnFileName = returnFileName.toLowerCase(); returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".")+1); if (returnFileName.equals("html") || returnFileName.equals("htm") || returnFileName.equals("shtml")){ contentType = "text/html"; } else if (returnFileName.equals("css")){ contentType = "text/css"; } else if (returnFileName.equals("xml")){ contentType = "text/xml"; } else if (returnFileName.equals("gif")){ contentType = "image/gif"; } else if (returnFileName.equals("jpeg") || returnFileName.equals("jpg")){ contentType = "image/jpeg"; } else if (returnFileName.equals("js")){ contentType = "application/x-javascript"; } else if (returnFileName.equals("atom")){ contentType = "application/atom+xml"; } else if (returnFileName.equals("rss")){ contentType = "application/rss+xml"; } else if (returnFileName.equals("mml")){ contentType = "text/mathml"; } else if (returnFileName.equals("txt")){ contentType = "text/plain"; } else if (returnFileName.equals("jad")){ contentType = "text/vnd.sun.j2me.app-descriptor"; } else if (returnFileName.equals("wml")){ contentType = "text/vnd.wap.wml"; } else if (returnFileName.equals("htc")){ contentType = "text/x-component"; } else if (returnFileName.equals("png")){ contentType = "image/png"; } else if (returnFileName.equals("tif") || returnFileName.equals("tiff")){ contentType = "image/tiff"; } else if (returnFileName.equals("wbmp")){ contentType = "image/vnd.wap.wbmp"; } else if (returnFileName.equals("ico")){ contentType = "image/x-icon"; } else if (returnFileName.equals("jng")){ contentType = "image/x-jng"; } else if (returnFileName.equals("bmp")){ contentType = "image/x-ms-bmp"; } else if (returnFileName.equals("svg")){ contentType = "image/svg+xml"; } else if (returnFileName.equals("jar") || returnFileName.equals("var") || returnFileName.equals("ear")){ contentType = "application/java-archive"; } else if (returnFileName.equals("doc")){ contentType = "application/msword"; } else if (returnFileName.equals("pdf")){ contentType = "application/pdf"; } else if (returnFileName.equals("rtf")){ contentType = "application/rtf"; } else if (returnFileName.equals("xls")){ contentType = "application/vnd.ms-excel"; } else if (returnFileName.equals("ppt")){ contentType = "application/vnd.ms-powerpoint"; } else if (returnFileName.equals("7z")){ contentType = "application/x-7z-compressed"; } else if (returnFileName.equals("rar")){ contentType = "application/x-rar-compressed"; } else if (returnFileName.equals("swf")){ contentType = "application/x-shockwave-flash"; } else if (returnFileName.equals("rpm")){ contentType = "application/x-redhat-package-manager"; } else if (returnFileName.equals("der") || returnFileName.equals("pem") || returnFileName.equals("crt")){ contentType = "application/x-x509-ca-cert"; } else if (returnFileName.equals("xhtml")){ contentType = "application/xhtml+xml"; } else if (returnFileName.equals("zip")){ contentType = "application/zip"; } else if (returnFileName.equals("mid") || returnFileName.equals("midi") || returnFileName.equals("kar")){ contentType = "audio/midi"; } else if (returnFileName.equals("mp3")){ contentType = "audio/mpeg"; } else if (returnFileName.equals("ogg")){ contentType = "audio/ogg"; } else if (returnFileName.equals("m4a")){ contentType = "audio/x-m4a"; } else if (returnFileName.equals("ra")){ contentType = "audio/x-realaudio"; } else if (returnFileName.equals("3gpp") || returnFileName.equals("3gp")){ contentType = "video/3gpp"; } else if (returnFileName.equals("mp4") ){ contentType = "video/mp4"; } else if (returnFileName.equals("mpeg") || returnFileName.equals("mpg") ){ contentType = "video/mpeg"; } else if (returnFileName.equals("mov")){ contentType = "video/quicktime"; } else if (returnFileName.equals("flv")){ contentType = "video/x-flv"; } else if (returnFileName.equals("m4v")){ contentType = "video/x-m4v"; } else if (returnFileName.equals("mng")){ contentType = "video/x-mng"; } else if (returnFileName.equals("asx") || returnFileName.equals("asf")){ contentType = "video/x-ms-asf"; } else if (returnFileName.equals("wmv")){ contentType = "video/x-ms-wmv"; } else if (returnFileName.equals("avi")){ contentType = "video/x-msvideo"; } return contentType; } }  
相關文章
相關標籤/搜索