小编典典

如何在Android中显式禁用HTTP连接的分流模式?

java

我的目标是使用的Android 4.0中的REST
Web服务HttpsURLConnection。除非我尝试执行POST某些操作,否则此方法效果很好。这是相关的代码部分:

   connection.setDoOutput(true);
   connection.setChunkedStreamingMode(0);

   ByteArrayOutputStream out = new ByteArrayOutputStream();
   serializeObjectToStream(out, object);
   byte[] array = out.toByteArray();
   connection.getOutputStream().write(array, 0, array.length);

这将引发以下异常:

   java.net.HttpRetryException: Cannot retry streamed HTTP body

通过调试,我意识到通过的输出流connection.getOuputStream()是类型的,ChunkedOutputStream并且通过挖掘Android源代码,我发现如果需要重试请求(无论出于何种原因),它就会抛出上述异常,因为它指出了这一点。是
不是RetryableOutputStream它想在那里。

现在的问题是:如何使HttpsURLConnection返回这样的RetryableOutputStream,或者如何防止正确地对分块的请求进行编码?我
以为 我已经这样做了setChunkedStreamingMode(0),但是显然事实并非如此……

[编辑]

否,实现的实现会java.net.HTTPUrlConnection忽略0或更低的流模式:

 public void setChunkedStreamingMode(int chunkLength) {
    [...]
    if (chunkLength <= 0) {
        this.chunkLength = HttpEngine.DEFAULT_CHUNK_LENGTH;
    } else {
        this.chunkLength = chunkLength;
    }
}

阅读 216

收藏
2020-11-16

共1个答案

小编典典

mm!解决方案是根本不从客户端代码调用setChunkedStreamingMode()(甚至setFixedStreamingMode())!“
-1”是fixedLength和chunkedLength的内部默认值,不能在客户端设置,因为将值设置为小于或等于“
0”可以使其默认为HttpEngine.DEFAULT_CHUNK_LENGTH(或在固定流模式下抛出异常)。

2020-11-16