Ask the first :
>>>>>>>>>>>>>>>>>>>>>>>>
range:bytes=1024-    // Breakpoint continuation request must contain the request header
host:192.168.118.120:8888
accept:*/*
>>>>>>>>>>>>>>>>>>>>>>>>

In response to the first :
>>>>>>>>>>>>>>>>>>>>>>>>
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=WebGoat-OWASP_Developer-5.2.zip
Accept-Ranges: bytes
Content-Range: bytes 1024-304974591/304974592
Content-Type: application/x-download;charset=utf-8
Content-Length: 304973568   // It should be noted that the length value here is the length required by the request , namely 304974591 -
>>>>>>>>>>>>>>>>>>>>>>>>

The first two requests :
>>>>>>>>>>>>>>>>>>>>>>>>
range:bytes=10-1033  // Breakpoint continuation request must contain the request header
host:192.168.118.120:8888
accept:*/*
>>>>>>>>>>>>>>>>>>>>>>>>

Response to the first two :
>>>>>>>>>>>>>>>>>>>>>>>>
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=WebGoat-OWASP_Developer-5.2.zip
Accept-Ranges: bytes
Content-Range: bytes 10-1033/304974592
Content-Type: application/x-download;charset=utf-8
Content-Length: 1024  // It should be noted that the length value here is the length required by the request , namely 1033- 10
>>>>>>>>>>>>>>>>>>>>>>>>

/**
     * Download a file that already exists on the server , Support breakpoint renewal
     *
     * @param request
     *            Request object
     * @param response
     *            The response object
     * @param path
     *            File path ( absolute )
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, File proposeFile) {
        LOGGER.debug(" Download file path :" + proposeFile.getPath());
        InputStream inputStream = null;
        OutputStream bufferOut = null;
        try {
            // Set response header
            long fSize = proposeFile.length();
            response.setContentType("application/x-download");
            // Content-Disposition: attachment; filename=WebGoat-OWASP_Developer-5.2.zip
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(proposeFile.getName(), ENCODING));
            // Accept-Ranges: bytes
            response.setHeader("Accept-Ranges", "bytes");
            long pos = 0, last = fSize - 1, sum = 0;//pos Start reading location ;  last Last read location ;  sum Record the total number of bytes that have been read
            if (null != request.getHeader("Range")) {
                // Breakpoint continuation
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                try {
                    // The situation a :RANGE: bytes=2000070- Scenario two :RANGE: bytes=2000070-2000970
                    String 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;
                }
            }
            long rangLength = last - pos + 1;// Total number of bytes to read
            // Content-Range: bytes 10-1033/304974592
            String contentRange = new StringBuffer("bytes ").append(pos).append("-").append(last).append("/").append(fSize).toString();
            response.setHeader("Content-Range", contentRange);
            // Content-Length: 1024
            response.addHeader("Content-Length", String.valueOf(rangLength));             // Skip the downloaded part , For subsequent downloads
            bufferOut = new BufferedOutputStream(response.getOutputStream());
            inputStream = new BufferedInputStream(new FileInputStream(proposeFile));
            inputStream.skip(pos);
            byte[] buffer = new byte[1024];
            int length = 0;
            while (sum < rangLength) {
                length = inputStream.read(buffer, 0, ((rangLength - sum) <= buffer.length ? ((int) (rangLength - sum)) : buffer.length));
                sum = sum + length;
                bufferOut.write(buffer, 0, length);
            }
        } catch (Throwable e) {
            if (e instanceof ClientAbortException) {
                // The browser clicks cancel
                LOGGER.info(" User cancels 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();
            }
        }
    }

An error in development :

org.apache.catalina.connector.ClientAbortException: Connection reset by peer: socket write error

The reason for this error is that Content-Length: 1024 Inconsistent with the length of the first request , As a result, the requester refused

http Breakpoint continuation principle :http head Range、Content-Range

The so-called breakpoint continuation , This means starting where the file has already been downloaded . In previous versions HTTP The protocol does not support breakpoints ,HTTP/1.1 From the beginning . It is generally used when downloading breakpoints Range and Content-Range Entity head .

Range

Used in the request header , Specify the position of the first byte and the position of the last byte , General format :

Range:(unit=first byte pos)-[last byte pos]

Content-Range

For response headers , Specifies the insertion position of a part of the entire entity , He also indicates the length of the whole entity . At the server, a partial response is returned to the client , It must describe the scope of the response and the entire entity length . General format :

Content-Range: bytes (unit first byte pos) - [last byte pos]/[entity legth]

Request to download the entire file :

  1. GET /test.rar HTTP/1.1
  2. Connection: close
  3. Host: 116.1.219.219
  4. Range: bytes=0-801 // The general request to download the entire file is bytes=0- Or not with this head

General normal response

  1. HTTP/1.1 200 OK
  2. Content-Length: 801
  3. Content-Type: application/octet-stream
  4. Content-Range: bytes 0-800/801 //801: Total file size

Here's an excerpt from the Internet , And it has been revised : The original content is wrong, resulting in the pit

The principle of breakpoint continuation

In fact, the principle of breakpoint continuation is very simple , Is in the Http The request is different from the general download .       
For example , When the browser requests a text on the server , The requests are as follows :       
Suppose the server domain name is wwww.sjtu.edu.cn, The file named 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 , Search for the requested file as required , Extracting information from a file , And then back to the browser , The return message is as follows :

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, 30 Apr 2001 12:56:11 GMT

The so-called breakpoint continuation , This means starting where the file has already been downloaded . So in the client browser to Web Add one more message to the server -- Where to start .       
Here's one made up by myself " browser " To send a request message to Web The server , Demand from 2000070 Byte start .       
GET /down.zip HTTP/1.0        
User-Agent: NetFox        
RANGE: bytes=2000070-        
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

Take a closer look and you'll find one more line RANGE: bytes=2000070-        
This line tells the server down.zip This file comes from 2000070 The byte starts to pass , The first byte doesn't need to be transferred .       
After the server receives this request , The information returned is as follows :       
206        
Content-Length=106585958       
Content-Range=bytes 2000070-106786027/106786028        
Date=Mon, 30 Apr 2001 12:55:20 GMT        
ETag=W/"02ca57e173c11:95b"       
Content-Type=application/octet-stream        
Server=Microsoft-IIS/5.0        
Last-Modified=Mon, 30 Apr 2001 12:55:20 GMT

Compare with the information returned by the previous server , You'll see the change :

Content-Length=106585958   
Content-Range=bytes 2000070-106786027/106786028        
The return code is also changed to 206 了 , Instead of 200 了 .

Knowing the above principle , You can continue the programming breakpoint

Java The key points to achieve breakpoint continuation

  1. (1) How to achieve submission RANGE: bytes=2000070-.
    Of course, with the original Socket It can be done for sure , But that's too much trouble , Actually Java Of net This functionality is provided in the package . The code is as follows :

    URL url = new URL("http://www.sjtu.edu.cn/down.zip");

    HttpURLConnection httpConnection =
    (HttpURLConnection)url.openConnection();

    // Set up User-Agent

    httpConnection.setRequestProperty("User-Agent","NetFox");

    // Set the starting position of breakpoint continuation

    httpConnection.setRequestProperty("RANGE","bytes=2000070");

    // Get the input stream

    InputStream input = httpConnection.getInputStream();

    The byte stream taken from the input stream is down.zip File from the 2000070 The starting byte stream .
    Everyone to see , In fact, breakpoint continuation is used Java It's very simple to realize .
    The next thing to do is how to save the stream to the file .

  2. The way to save the file .

    I'm going to use IO In bag RandAccessFile class .

    The operation is quite simple , Assuming that the 2000070 Start saving the file at , The code is as follows :

    RandomAccess oSavedFile = new
    RandomAccessFile("down.zip","rw");

    long nPos = 2000070;

    // Locate the file pointer to nPos Location

    oSavedFile.seek(nPos);

    byte[] b = new byte[1024];

    int nRead;

    // Read in byte stream from input stream , And write it to a file

    while((nRead=input.read(b,0,1024)) > 0)

    {

    oSavedFile.write(b,0,nRead);

    }

What about? , Simple enough .
The next step is to integrate it into a complete program . Including a series of thread control and so on .

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

java Implementation of breakpoint continuation of more related articles

  1. use Java Implement breakpoint continuation (HTTP)

    The principle of breakpoint continuation In fact, the principle of breakpoint continuation is very simple , Is in the Http The request is different from the general download .  For example , When the browser requests a text on the server , The requests are as follows :  Suppose the server domain name is wwww.sjtu.edu ...

  2. use Java The basic idea and code to achieve breakpoint continuation

    use Java The basic idea and code to achieve breakpoint continuation   URL url = new URL(http://www.oschina.net/no-exist.zip); HttpURLConnection http ...

  3. use Java Implementation of breakpoint continuation reference (HTTP)

    The principle of breakpoint continuation In fact, the principle of breakpoint continuation is very simple , Is in the Http The request is different from the general download .        For example , When the browser requests a text on the server , The requests are as follows :        Suppose the server domain name is ...

  4. Java ftp Breakpoint continuation

    FtpTransFile class import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExcept ...

  5. Java Implement breakpoint continuation

    principle : The key of breakpoint continuation is breakpoint , So we should design the transmission protocol well , Pictured above , I customized an interaction protocol , Every download request will bring the starting point of the download , In this way, we can support downloading from breakpoints , Actually HTTP This is also the principle of breakpoint continuation in , stay H ...

  6. java Server side breakpoint continuation

    Servlet Java Code Copy code Collection code import java.io.BufferedOutputStream; import java.io.File; import java.io.IO ...

  7. java download Breakpoint continuation

    1 import java.io.BufferedInputStream; 2 import java.io.File; 3 import java.io.FileInputStream; 4 imp ...

  8. java File breakpoint continuation upload download solution

    Only the back-end code is written here , The basic idea is , The front end splits the files , Then every time I visit the upload interface , Pass in parameters... To the back end : What is the current file , And the total number of slices Just post the code , I annotated most of the incomprehensible : Upload file entity class : See ...

  9. java Support breakpoint file upload and download components

    java Between two servers , Big file upload ( Sequel ), Adopted Socket Communication mechanism and JavaIO There are two technical points , The idea is as follows : Realize the idea : 1. clothing : utilize ServerSocket Set up server , Open the corresponding port , Make a long connection ...

Random recommendation

  1. [ Poached ASP.NET Web API2 methodology ](3-5) Routing constraints

    problem How to limit the value of parameters in routing . Solution ASP.NET WEB API Allow us to pass IHttpRouteConstraint Interface set routing constraints . Both centralized routing and direct routing can be used IHttpRou ...

  2. Easyui Layout Center Full screen method extension

    $.extend($.fn.layout.methods, { full : function (jq) { return jq.each(function () { var layout = $(t ...

  3. windows7 install phpnow Apache Can't operate without administrator permission Windows NT Solutions to service

    Science Popularization :PHPnow What is it? ?        Win32 Green free Apache + PHP + MySQL Environment package . Simple installation . Quickly build virtual machine PHP Environmental Science , Can install Discuz! ...

  4. x^y=(x&amp;~y)|(~x&amp;y) prove

    The best proof I've ever seen is the Venn diagram :( First of all, we should know that binary Boolean algebra is a special case of set , So the X and Y As two sets , The conclusion is true , So it also holds in binary Boolean algebra .) The circle on the left is X, The circle on the right is Y. If it is OR That is to say, take or , The white one in the middle ...

  5. poll mechanism analysis

    More documents :http://pan.baidu.com/s/1sjzzlDF linux poll/select Usage and simple implementation in character drive 1.poll and select Use non blocking I/O Our applications often make ...

  6. 2016, except DevOps, Enterprises should also know CMDB!

    CMDB yes Configuration Management Database( Configuration management database ) For short ,CMDB Storage and management enterprise IT Various configuration information of devices in the architecture , It's tied to all service support and service delivery processes ...

  7. SVN Remember how to change your user name and password

    I came across one today SVN Check out code user authentication issues . Because I've been involved in several projects recently , I'm too busy for a moment . So I hope to follow my colleagues in the probation period to help me test if there is any problem with the newly modified function . But the colleague doesn't have permission in the project , It happens to be Sunday ...

  8. [ turn ]JS inherited 5 Type of implementation

    Reference link : http://yahaitt.iteye.com/blog/250338 Although the book has talked about the way of inheritance , But every time I look at these things, I get something new , So take it out and put it alone . 1. The object pretended to be funct ...

  9. Windows 8 application development - Application bar

    original text :Windows 8 application development - Application bar      Through the application bar (AppBar) Various application commands can be displayed to users when needed . The application bar provides various commands related to the user's current page or currently selected content . By default , The application bar is hidden ...

  10. turn :MAVEN Depends on local engineering or warehouse JAR package ?

    I believe everyone has met  maven Configuration dependency or  jar Package or Engineering , In the process of development , Of course, what we need to introduce is engineering , Look at  maven When it comes to dependent files , You can see the source code directly . One . Local projects depend on For example ...