OkHttp版本:2.0.0
我通过Google Play收到了以下异常堆栈跟踪:
java.lang.IllegalStateException:无法流式传输请求体 分块编码或已知内容长度!在 com.squareup.okhttp.internal.http.HttpTransport.createRequestBody(HttpTransport.java:68) 在 com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:254) 在com.squareup.okhttp.Call.getResponse(Call.java:198)at com.squareup.okhttp.Call.access $ 200(Call.java:36)at com.squareup.okhttp.Call $ AsyncCall.execute(Call.java:143)at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587) 在java.lang.Thread.run(Thread.java:848)
这正是提出请求的方式:
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.addHeader("User-Agent", userAgent);
requestBuilder.addHeader("Accept", "application/hal+json");
requestBuilder.url(transformedURL);
RequestBody requestBody = body == null ? null : RequestBody.create(MediaType.parse("application/json"), gson.toJson(body));
requestBuilder.method(method, requestBody);
okHttpClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() { ...
起初它似乎与this bug有关,但它已被修复。此外,我们在开发期间多次使用空体测试POST请求。
这个应用程序只执行GET和POST请求。
可能导致此错误的原因是什么?
答案 0 :(得分:0)
您是如何创建HTTP请求的?如果您可以创建可重现的测试用例,请向OkHttp提交一个错误,我们将会修复。
答案 1 :(得分:0)
以下代码抛出了这个异常:
包okhttp3.internal.http;
<强> Http1xStream.java 强>
@Override public Sink createRequestBody(Request request, long contentLength) throws IOException {
if ("chunked".equalsIgnoreCase(request.header("Transfer-Encoding"))) {
// Stream a request body of unknown length.
return newChunkedSink();
}
if (contentLength != -1) {
// Stream a request body of a known length.
return newFixedLengthSink(contentLength);
}
throw new IllegalStateException(
"Cannot stream a request body without chunked encoding or a known content length!");
}
要解决此问题,我需要在我的请求中添加一个标头,可以像这样添加:.addHeader("Transfer-Encoding","chunked")
:
OP的样本:
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.addHeader("User-Agent", userAgent);
requestBuilder.addHeader("Accept", "application/hal+json");
<强> requestBuilder..addHeader("Transfer-Encoding","chunked")
强>
requestBuilder.url(transformedURL);