Android HttpPost因“错误”而失败;无法使用不可重复的请求实体“重试请求”;
我试图在android mobile中通过HttpClient将照片上传到服务器,但有时我会遇到这个错误,这种情况并不总是发生。有人知道怎么解决吗 我的代码如下:Android HttpPost因“错误”而失败;无法使用不可重复的请求实体“重试请求”;,android,Android,我试图在android mobile中通过HttpClient将照片上传到服务器,但有时我会遇到这个错误,这种情况并不总是发生。有人知道怎么解决吗 我的代码如下: HttpClient client =new DefaultHttpClient(); HttpPut httpPut = new HttpPut(uploadUrl); InputStream in =null; HttpResponse response =null; try {
HttpClient client =new DefaultHttpClient();
HttpPut httpPut = new HttpPut(uploadUrl);
InputStream in =null;
HttpResponse response =null;
try {
in = new FileInputStream(filepath);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(in);
entity.setContentLength(new File(basepath+path).length());
httpPut.setEntity(entity);
response = client.execute(httpPut);
System.out.println(response.getStatusLine());
consume(response.getEntity());
}
错误信息:
11-22 10:32:50.370: W/System.err(15224): org.apache.http.client.ClientProtocolException
11-22 10:32:50.370: W/System.err(15224): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:557)
11-22 10:32:50.370: W/System.err(15224): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 10:32:50.370: W/System.err(15224): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-22 10:32:50.370: W/System.err(15224): at com.hp.nimbus.android.skydrive.util.SkyDriveUtils_Rest.doUploadPhoto(SkyDriveUtils_Rest.java:203)
11-22 10:32:50.380: W/System.err(15224): at com.hp.nimbus.android.skydrive.util.SkyDriveUtils_Rest.uploadPhoto(SkyDriveUtils_Rest.java:250)
11-22 10:32:50.380: W/System.err(15224): at com.hp.nimbus.android.skydrive.FolderMonitorService$1.onEvent(FolderMonitorService.java:36)
11-22 10:32:50.380: W/System.err(15224): at android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
11-22 10:32:50.380: W/System.err(15224): at android.os.FileObserver$ObserverThread.observe(Native Method)
11-22 10:32:50.380: W/System.err(15224): at android.os.FileObserver$ObserverThread.run(FileObserver.java:88)
11-22 10:32:50.380: W/System.err(15224): Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
11-22 10:32:50.380: W/System.err(15224): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:419)
11-22 10:32:50.380: W/System.err(15224): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-22 10:32:50.390: W/System.err(15224): ... 8 more
这意味着初始请求失败,因为它是一个流,所以不能重复它 如果删除
FileInputStream
而改用,我相信它将是可重复的
您也不必设置长度。回答此问题可能会有点晚,但对于登录此页面的用户来说,出现异常的原因是
BasicHttpEntity
不允许重复请求。您需要使用适当的HttpEntity
实现
对于这个问题,正如Matthew Flaschen在另一个答案中提到的,它将是
FileEntity
,但对于大多数其他情况,可以使用它,允许重复请求。您好,谢谢您的回答。我以前试过FileEntity,问题是上传服务器不支持FileEntity,我必须使用FileInputStream。您提到初始请求失败,它能知道失败的原因吗?不支持FileEntity
听起来很奇怪。对于一个简单的修复,请尝试将您的实体包装在一个BufferedHttpEntity中-这将使其可重复,但这样做会消耗更多的内存。