This breakpoint download can be applied to the browser or the download of thunder and other download tools, the implementation of a variety of ways, this article only study the single-threaded download. Thunder and other download tools will take the initiative to block the download resources and record the starting position of each block, and then based on system performance. Multi-threaded download.
1. Fundamentals
From the request header's range information to get the size of the downloaded file, and then create the response OutputStream to the client (browser or thunder and other download tools) write, write and use the header inside the " Content-range ", let the client know where to start writing;
In terms of reading network resources, using httpclient to simulate request requests, initiating a post or GET request, just this request is a little different from the general request: you need to bring the range information. Tells the program which location to start reading data from.
2. Java components that need to be used
- Httpservletrequest/response
- HttpClient
- Servletoutputstream
- Bufferedinputstream
3. Code implementation
/** * @desc Breakpoint Download Tool method * @param request * @param response * @param filelength * @param contentType * @param fileName * @para M fileId */public static void Resumedownload (HttpServletRequest request,httpservletresponse response, Long filelength, String contenttype,string fileName, String fileId) {Servletoutputstream out = Null;response.reset ();//Record the start point of a breakpoint continuation long pos = 0;if (null! = Request.getheader ("Range")) {response.setstatus (httpservletresponse.sc_partial_content); try {pos = Long.parselong (Request.getheader ("Range"). ReplaceAll ("bytes=", ""). ReplaceAll ("-.*", ""));} catch (NumberFormatException e) {logger.error (E.getmessage (), e);p os = 0;} String Contentrange = new StringBuffer ("bytes"). Append (pos + ""). Append ("-"). Append ((Filelength.intvalue ()-1) + ""). AP Pend ("/"). Append (Filelength.intvalue () + ""). toString (); Response.setheader ("Content-range", Contentrange);} Response.setheader ("accept-ranges", "bytes"); Response.setheader ("Content-length", string.valueof ( Filelength.intvalue ()-POS)); reSponse.setcharacterencoding ("UTF-8"); Response.setcontenttype (ContentType); Response.setheader (" Content-disposition "," attachment;filename=\ "" + filename + "\" "); try {out = Response.getoutputstream ();} catch ( IOException e) {logger.error (E.getmessage (), e);} Breakpoint Download Closeablehttpclient httpClient = Httpclients.createdefault (); HttpPost HttpPost = new HttpPost (sysconf.getstring ("Fezo.download.url")); list<namevaluepair> Nvps = new arraylist<namevaluepair> (); Nvps.add (New Basicnamevaluepair ( Sysconf.getstring ("Fezo.download.param"), fileId)); HttpResponse HttpResponse = null; Bufferedinputstream input = null;try {httppost.setentity (new urlencodedformentity (Nvps)); Httppost.setheader ("Range" , "bytes=" + pos + "-"); HttpResponse = Httpclient.execute (httppost); input = new Bufferedinputstream ( Httpresponse.getentity (). getcontent ()); byte[] buffer = new Byte[commonconstants.buffer_size];int len = -1;while (len = Input.read (buffer))! =-1) {out.write (buffer, 0, Len);} Out.flush (); Out.close (); InpuT.close ();} catch (Unsupportedencodingexception e) {logger.error (E.getmessage (), e);} catch (Clientprotocolexception e) { Logger.error (E.getmessage (), E); catch (IOException e) {//can ignore this exception. It is possible that the user paused the download, or the download tool such as Thunderbolt downloads the block download} finally {try {if (httpClient! = null) Httpclient.close ();} catch (IOException e) {logger.error ( E.getmessage (), E);}}
>>> Click here to download the code
4. Key points and difficulties
-Get the output flow of response to provide the client with the download function, rather than simply write the data to a detailed file, the core code: Out = Response.getoutputstream ();
-processing of information such as "Range" and "Conent-range" in the header information;
-Thunder and other multi-threaded block download client download processing: or to handle the "Range" and "Conent-range" and other head information, Thunderbolt will take the initiative to file the contents of the block, record the starting position.
Java implementation of Breakpoint download