Java implements GZIP decompression of HTML Web pages
Found in the Web Capture, many of the returned pages are compressed, such as access to the Google home page, the returned header file contains content-encoding gzip
The use of gzip can save a lot of web traffic, in the case of a certain speed, can improve access efficiency, we use Java Access when we can get the gzip return, and how do we parse the returned gzip?
Let's take a visit to http://www.baidu.com/as an example
We do not return gzip compressed data directly when we use the URL's OpenStream method, because the time to return to Gzip is to determine if the browser supports gzip compression, so when we request data, we add the gzip-enabled request header to the HTTP request header to
Add Conn.setrequestproperty ("accept-encoding", "gzip,deflate"); just tell the server that your browser supports gzip decompression.
URL url = new URL ("http://www.baidu.com/"); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestproperty ("Accept-Encoding", "gzip, Deflate "); Conn.connect (); InputStream in = Conn.getinputstream (); BufferedReader bin = new BufferedReader (new InputStreamReader (in, "GB2312")); String s = Null;while ((S=bin.readline ())!=null) {System.out.println (s);} Bin.close ();
No Conn.setrequestproperty ("accept-encoding", "gzip,deflate");
Add Conn.setrequestproperty ("accept-encoding", "Gzip,deflate"), is garbled, this is because the server to the return content gzip compression for the sake of, We just have to determine if the return header contains content-encoding gzip, we can determine whether the data is compressed, treat the compressed data we just have to do gzip decompression just fine
Simply add the above code to Gzipinputstream Gzin = new Gzipinputstream (in) and bufferedreader bin = new BufferedReader (new InputStreamReader (In, "GB2312")); BufferedReader bin = new BufferedReader (new InputStreamReader (Gzin, "GB2312"));
Of course if you need gzip decompression, just determine if the return data header contains content-encoding gzip.
Java Cashing HTML Web page gzip decompression