Java implementation of Breakpoint download

Source: Internet
Author: User
Tags getmessage

This breakpoint download can be applied to the browser or thunder and other download tools download, the implementation of a variety of ways, this article only study single-threaded download, thunder and other download tools will automatically download the resources to block and record the starting position of each block, and then according to system performance, from multi-threaded download.

1. Fundamentals

From the request header's range information to get the size of the downloaded file, and then create response OutputStream to the client (browser or thunder and other download tools) to write, write and use the header inside the " Content-range ", let the client know from which location to start writing;

To read network resources, use HttpClient to simulate request requests, initiate a post or GET request, but this request is a little different from the general request: you need to bring the range information to tell the program where to start reading the data.

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 for the user to pause the download, or a download tool such as Thunderbolt download the block downloads} finally {try {if (httpClient! = null) Httpclient.close ();} CA TCH (IOException e) {logger.error (E.getmessage (), E);}}}

4. Key points and difficulties

-Get the output flow of response to provide download function to the client, instead of simply writing the data to a specific 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 automatically block the contents of the file, record the starting position.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java implementation of Breakpoint download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.