iftach barshem
iftach barshem

Reputation: 527

How to send file in parts using header "Range"?

I would like to send big file by dividing it to small parts and send them separately. I tried to use the hedder "Range" and got "org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity".

// create authenticate client
DefaultHttpClient client = new DefaultHttpClient();

// create HTTP put with the file
HttpPut httpPut = new HttpPut(url);
final File recordingFile = new File(mDir, mName);
long fileLength = recordingFile.length();
for (int i=0; i < fileLength; i += 4096) {
    int length = Math.min(4096, (int)recordingFile.length() - i);
    InputStreamEntity entity = new InputStreamEntity(inputStream, length);
    httpPut.setEntity(entity);
    httpPut.addHeader("Connection", "Keep-Alive");
    httpPut.addHeader("Range", "bytes=" + i + "-" + (i + length));

    // Execute
    HttpResponse res = client.execute(httpPut);
    int statusCode = res.getStatusLine().getStatusCode();
}

I also tried "Content-Range" header (instead of "Range") and I got the same exception.

httpPut.addHeader("Content-Range", "bytes=" + i + "-" + (i + length) + "/" + fileLength);
httpPut.addHeader("Accept-Ranges", "bytes");

Upvotes: 1

Views: 1945

Answers (1)

tibtof
tibtof

Reputation: 7967

You repeatedly send multiple of 4096 bits. E.g. let's take the first two steps: i = 0 Send range 0-4096 i = 4096 Send range 4096-8192.

Fix this lines:

for (int i=0; i <= fileLength; i += 4097) {
    int length = Math.min(4096, (int)recordingFile.length() - i + 1);
    /*...*/
}

and it should work fine.

Update: Maybe the problem is that for some reasons (e.g. authentication failure) it tries to resend the same chunk again, in which case the inputstream is already consumed. Try using a ByteArrayEntity instead of InputStreamEntity, something like this:

ByteArrayInputStream bis = new ByteArrayInputStream(recordingFile);
for (int i=0; i <= fileLength; i += 4097) {
    int length = Math.min(4096, (int)recordingFile.length() - i + 1);
    byte[] bytes = new byte[length];
    bis.read(bytes);
    ByteArrayEntity entity = ByteArrayEntity(bytes);
    /*...*/
}

Upvotes: 1

Related Questions