Paul Taylor
Paul Taylor

Reputation: 13140

Problem gzipping HttpPost body using Apache Client 4.1.1

I need to send a HTTPPost with body gzipped, the server accepts non gzipped data also but would prefer it gzipped, so Im trying to convert some existing workign code to use gzip The data is currently set with

    httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Ive tried sublclassing 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);
    }
}

and changed to

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

and added

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

but now my request just time outs I think there must be something wrong with my GZIpWrapper but Im not sure what.

On another note I looked at the http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientGZipContentCompression.java. example. Aside from the fact that I dont like interceptors because it is difficult to follow program flow it doesnt make sense to me because the request header is set to tell the server to accept gzip data but nowhere does it actually gzip encode any data, it only unzips the response.

Upvotes: 1

Views: 1786

Answers (1)

ok2c
ok2c

Reputation: 27613

(1) GzipWrapper implementation is wrong. It transforms the entity content when writing it out to output stream but it still returns the Content-Length of the wrapped entity, this causing the server to expect more input than actually transmitted by the client.

(2) You completely misunderstand the purpose of the Accept-Encoding header

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

(3) ClientGZipContentCompression sample is correct. It does not compress outgoing request entity because it is not meant to do so. See point (2)

Upvotes: 2

Related Questions