er4z0r
er4z0r

Reputation: 4891

How do I differentiate between request and response in an HTTPURLConnection?

Hi I need to evaluate if a server supports gzip compression.

Therefore I want to set gzip as Accept-Encoding in my request and evaluate if the response of the server containts "Content-Encoding: gzip".

However I am not quite clear on how to do this with HTTPURLConnection. Especially when to query my Connection object about the response. I currently do:

HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
    con.setRequestProperty("Accept-Encoding", "gzip");
    System.out.println("Current Accept-Encoding: "+con.getRequestProperty("Accept-Encoding"));
    //check the response for the content-size
    float feedsize = con.getContentLength()/1024f;
    //the server uses transfer-encoding=chunked and does not specify
    //a content length
    if(con.getContentLength()==-1)
    {
        //count the content size manually
                    CountingInputStream counter = new CountingInputStream(con.getInputStream());
        while(counter.read()!=-1)
        {}
        feedsize=counter.getCount()/1024f;
    }
    con.disconnect();

Upvotes: 2

Views: 1699

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272207

Have a look at this OReilly article. It illustrates how to generate the request, and how to interrogate the response and then create the appropriate stream (normal or gzipped) dependent on what's being returned.

Upvotes: 2

Related Questions