开发者

how to get page source with content encoding gzip using httpClient?

I am using commons-httpclient 3.1 to read a html page source. It is working fine with all except pages with content encoding as gzip. I am getting incomplete page source.

For this page firefox is showing content encoding as gzip.

Below are the details

Response header:

status code: HTTP/1.1 200 OK
Date = Wed, 20 Jul 2011 11:29:38 GMT
Content-Type = text/html; charset=UTF-8
X-Powered-By = JSF/1.2
Set-Cookie = JSESSIONID=Zqq2Tm8V74L1LJdBzB5gQzwcLQFx1khXNvcnZjNFsQtYw41J7JQH!750321853; path=/; HttpOnly
Transfer-Encoding = chunked
Content- length =-1

My code to read response :

HttpClient httpclient = new HttpClient();
            httpclient.getParams().setParameter("http.connection.timeout",
                    new Integer(50000000));
            httpclient.getParams().setParameter("http.socket.timeout",
                    new Integer(50000000));


        // Create a method instance.
        GetMethod method = new GetMethod(url);



        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        BufferedReader reader = null;
            // Execute the method.
            int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + method.getStatusLine());
                strHtmlContent = null;
            } else {


                InputStream is = method.getResponseBodyAsStream();
                reader = new BufferedReader(new InputStreamReader(is,"ISO8859_8"));
                String line = null;
                String开发者_如何学CBuffer sbResponseBody = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    sbResponseBody.append(line).append("\n");
                }
                strHtmlContent = sbResponseBody.toString();


Upgrade to httpclient 4.1. It should support compression seamlessly.


I just incurred in this issue, which I solved as follows:

    URL url = new URL("http://www.megadevs.com");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    GZIPInputStream gzip = new GZIPInputStream(conn.getInputStream());
    int value = -1;
    String page = "";

    while ((value = gzip.read()) != -1) {
        char c = (char) value;
        page += c;
    }
    gzip.close();

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜