1

我想通过将大文件分成小部分并分别发送来发送大文件。我尝试使用 hedder“范围”并得到“org.apache.http.client.NonRepeatableRequestException:无法用不可重复的请求实体重试请求”。

// 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();
}

我还尝试了“Content-Range”标题(而不是“Range”),我得到了同样的例外。

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

1 回答 1

1

您重复发送多个 4096 位。例如,让我们采取前两个步骤: i = 0 发送范围 0-4096 i = 4096 发送范围4096 -8192。

修复此行:

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

它应该可以正常工作。

更新:也许问题是由于某些原因(例如身份验证失败)它尝试再次重新发送相同的块,在这种情况下输入流已经被消耗。尝试使用 ByteArrayEntity 而不是 InputStreamEntity,如下所示:

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);
    /*...*/
}
于 2012-05-23T15:26:15.470 回答