【问题标题】:Problem gzipping HttpPost body using Apache Client 4.1.1使用 Apache Client 4.1.1 压缩 HttpPost 正文的问题
【发布时间】:2011-05-11 10:12:31
【问题描述】:

我需要发送一个带有 gzip 的正文的 HTTPPost,服务器也接受非 gzip 压缩的数据,但更喜欢它 gzip,所以我试图将一些现有的 workign 代码转换为使用 gzip 数据当前设置为

    httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

我尝试子类化 HttpEntityWrapper

static class GzipWrapper extends HttpEntityWrapper
{
    public GzipWrapper(HttpEntity wrapped)
    {
        super(wrapped);
    }

    public void writeTo(OutputStream outstream)
         throws IOException
    {
        GZIPOutputStream gzip = new GZIPOutputStream(outstream);
        super.writeTo(gzip);
    }
}

改成

    httpMethod.setEntity(new GzipWrapper(
          new UrlEncodedFormEntity(nameValuePairs)));

并添加

    if (!httpMethod.containsHeader("Accept-Encoding"))
    {
        httpMethod.addHeader("Accept-Encoding", "gzip");
    }

但现在我的请求刚刚超时,我认为我的 GZIpWrapper 一定有问题,但我不确定是什么。

在另一张纸条上,我查看了http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientGZipContentCompression.java。例子。除了我不喜欢拦截器这一事实之外,因为很难遵循程序流程,这对我来说没有意义,因为请求标头设置为告诉服务器接受 gzip 数据,但实际上 gzip 并没有对任何数据进行编码,它只解压缩回应。

【问题讨论】:

    标签: java http httpclient http-post


    【解决方案1】:

    (1) GzipWrapper 实现错误。它在将实体内容写出到输出流时对其进行转换,但它仍然返回包装实体的 Content-Length,这导致服务器期望的输入比客户端实际传输的要多。

    (2) 你完全误解了Accept-Encoding 标头的用途

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

    (3) ClientGZipContentCompression 示例正确。它不压缩传出请求实体,因为它不打算这样做。见第(2)点

    【讨论】:

    • Thx Oleg,(好的,我现在明白了,当您设置请求 Accept-Encoding 标头时,它会告诉服务器它可以从服务器响应中接受哪些编码)
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多