Java implementation of breakpoints continue to pass

Source: Internet
Author: User

/*** Download files that already exist on the server, support the continuation of the breakpoint * *@paramRequest * Object *@paramResponse * Response Object *@parampath * file paths (absolute)*/     Public Static voidDownload (httpservletrequest request, httpservletresponse response, File proposefile) {logger.debug ("Download file path:" +Proposefile.getpath ()); InputStream InputStream=NULL; OutputStream Bufferout=NULL; Try {            //Setting the response header            LongFsize =proposefile.length (); Response.setcontenttype ("Application/x-download"); String Isofilename=Urlencoder.encode (Proposefile.getname (), ENCODING); Response.AddHeader ("Content-disposition", "attachment; Filename= "+isofilename); Response.AddHeader ("Content-length", String.valueof (fsize)); Response.setheader ("Accept-ranges", "bytes"); Longpos = 0, last = fSize-1; if(NULL! = Request.getheader ("Range")) {                //Breakpoint ContinuationResponse.setstatus (httpservletresponse.sc_partial_content); Try {                    //Scenario One: range:bytes=2000070-Scenario II: range:bytes=2000070-2000970String Numrang = Request.getheader ("Range"). ReplaceAll ("bytes=", "" "); String[] Strrange= Numrang.split ("-"); if(Strrange.length = = 2) {pos= Long.parselong (strrange[0].trim ()); Last= Long.parselong (strrange[1].trim ()); } Else{pos= Long.parselong (Numrang.replaceall ("-", "" "). Trim ()); }                } Catch(NumberFormatException e) {logger.error (Request.getheader ("Range") + "is not number!"); POS= 0; }} String Contentrange=NewStringBuffer ("bytes"). Append (NewLong (POS). toString ()). Append ("-"). Append (NewLong (fSize-1). toString ()). Append ("/"). Append (NewLong (fsize). ToString ()). ToString (); Response.setheader ("Content-range", Contentrange); //Skip the already downloaded sections for subsequent downloadsBufferout =NewBufferedoutputstream (Response.getoutputstream ()); InputStream=NewBufferedinputstream (NewFileInputStream (proposefile));            Inputstream.skip (POS); byte[] buffer =New byte[5 * 1024]; LongRanglength = last-pos + 1, sum = 0;//sum records how many bytes have been read in total            intLength = 0;  while(length = inputstream.read (buffer, 0, ((ranglength-sum) <= buffer.length?) ((int) (Ranglength-sum)): buffer.length))! =-1 && sum <ranglength) {Sum= Sum +length; Bufferout.write (Buffer,0, length); }        } Catch(Throwable e) {if(Einstanceofclientabortexception) {                //Browser Click to cancelLogger.info ("User canceled download!")); } Else{logger.info ("Download file failed ....");            E.printstacktrace (); }        } finally {            Try {                if(Bufferout! =NULL) {bufferout.close (); }                if(InputStream! =NULL) {inputstream.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }    

How the breakpoint continues to pass

In fact, the principle of the continuation of the breakpoint is very simple, is the Http request and the general download is different.
For example, when a browser requests a text on a server, the following requests are made:
Assume that the server domain name is wwww.sjtu.edu.cn and the file name is Down.zip.
Get/down.zip http/1.1
Accept:image/gif, Image/x-xbitmap, Image/jpeg, Image/pjpeg, application/vnd.ms-
Excel, Application/msword, Application/vnd.ms-powerpoint, */*
Accept-language:zh-cn
Accept-encoding:gzip, deflate
user-agent:mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection:keep-alive

After the server receives the request, it looks for the requested file, extracts the file information, and returns it to the browser, returning the following information:

200        
content-length=106786028         
accept-ranges=bytes        
Date=mon, 30 APR 2001 12:56:11 gmt        
etag=w/"02ca57e173c11:95b"         
content-type=application/octet-stream         
server=microsoft-iis/5.0        
Last-modified=mon, APR 2001 12:56:11 gmt     

The so-called breakpoint continuation, that is, the file has been downloaded from the place to continue to download. So add a piece of information when the client browser passes to the WEB server-where to start.        
The following is a "browser" made by yourself to pass the request information to the WEB server, starting from 2000070 bytes.        
Get/down.zip http/1.0         
user-agent:netfox        
range:bytes=2000070-         
accept:text/html, Image/gif, Image/jpeg, *; q=.2, */*; q=.2      

Look at it and you'll find a line range:bytes=2000070-        
This line means telling the server Down.zip This file is transmitted from 2000070 bytes, and the preceding bytes are not passed.        
After the server receives this request, the information returned is as follows:       
206        
content-length=106786028         
Content-range=bytes 2000070-106786027/106786028         
Date=mon, APR 2001 12:55:20 gmt        
etag=w/" 02ca57e173c11:95b "       
content-type=application/octet-stream         
server=microsoft-iis/5.0         
Last-modified=mon, APR 2001 12:55:20 gmt     

Compare the information returned by the previous server and you will find an additional line:
Content-range=bytes 2000070-106786027/106786028
The returned code is also changed to 206, not 200 anymore.

Knowing the above principle, it is possible to program the continuation of the breakpoint.

The key points for Java to implement the breakpoint continuous transmission
  1. (1) What method to implement the submission range:bytes=2000070-.
    Of course, with the most original Socket is certainly able to complete, but that is too much trouble, in fact, Java's net package provides this functionality. The code is as follows:

    URL url = new URL ("Http://www.sjtu.edu.cn/down.zip");
    HttpURLConnection httpconnection = (httpurlconnection) url.openconnection ();

    Set User-agent
    Httpconnection.setrequestproperty ("User-agent", "Netfox");
    Set the start point for a breakpoint to resume
    Httpconnection.setrequestproperty ("RANGE", "bytes=2000070");
    Get input stream
    InputStream input = Httpconnection.getinputstream ();

    The byte stream removed from the input stream is the byte stream that the Down.zip file starts with 2000070. You see, in fact, the continuation of the breakpoint in Java implementation is still very simple it. The next thing to do is how to save the obtained stream to the file.

  2. The method used to save the file.
    I am using the Randaccessfile class in the IO package.
    The operation is fairly straightforward, assuming that the file is saved from 2000070, the code is as follows:
    Randomaccess osavedfile = new Randomaccessfile ("Down.zip", "RW");
    Long NPos = 2000070;
    Locate the file pointer to the NPos location
    Osavedfile.seek (NPos);
    Byte[] B = new byte[1024];
    int nread;
    Reads a byte stream from the input stream and then writes to the file
    while ((Nread=input.read (b,0,1024)) > 0)
    {
    Osavedfile.write (B,0,nread);
    }

It's easy, too. The next thing to do is to integrate it into a complete program. Including a series of line program control system and so on.

NOTE: Reprint http://www.ibm.com/developerworks/cn/java/joy-down/index.html

Java implementation of breakpoints continue to pass

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.