无法重试具有不可重复请求实体的请求

2022-09-04 20:00:37

我正在使用java-http-client库和Apache Transport,它在客户端,Rails在服务器端。不时出现这样的 get 错误:

11-24 17:37:02.469: WARN/BaseActivity(5925): org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:557)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    at com.google.api.client.http.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:58)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:639)
    at com.sk.api.SkClient.updateUser(SkClient.java:157)
    at com.sk.api.SkClient$3.call(SkClient.java:76)
    at com.sk.api.SkClient$3.call(SkClient.java:71)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    at java.lang.Thread.run(Thread.java:1019)
    Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:413)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    ... 12 more

我该怎么做才能避免这种情况?


答案 1

我有一个类似的错误,因为我使用了计数InputStreamEntity,这是一个不可重复的http客户端。解决方案是使用BufferedHttpEntity,它将不可重复的httpclient转换为可重复的httpclient。

ParcelFileDescriptor fileDescriptor = this.getContentResolver().openFileDescriptor(uri, "r");
            InputStream in = this.getContentResolver().openInputStream(uri);

            CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
            entity.setUploadListener(this);
            entity.setContentType("binary/octet-stream");
            entity.setChunked(true); 
        
            BufferedHttpEntity myEntity = null;
            try {
                myEntity = new BufferedHttpEntity(entity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            put.setEntity(myEntity);

答案 2

我把它当作傻瓜解决了:

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentType contentType = ContentType.create("image/jpeg", Consts.ISO_8859_1);
entityBuilder.addBinaryBody(PARAM_ATTACHMENT, new File(filepath), contentType, StringUtils.getFileName(filepath));