我想将大文件分成小部分并分别发送。 我试图使用hedder“Range”并获得“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");
答案 0 :(得分:1)
您反复发送多个4096位。例如。让我们采取前两个步骤: i = 0 发送范围0- 4096 我= 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);
/*...*/
}