有些網站回傳網頁會進行內容壓縮,壓縮方法常見有gzip或deflate,
可由回傳內容的ContentEncoding標頭決定如何處理回傳的壓縮內容。
以Java為例,解壓縮寫法如下:
// 設定下載網址
URL url = new URL("http://comment.bilibili.tv/29545595.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestProperty("Accept-Encoding", "identity");
// 連線取得網頁輸入流
conn.connect();
System.out.printf("con.getContentEncoding()=%s\n",conn.getContentEncoding());
InputStream in = conn.getInputStream();
if(conn.getContentEncoding().equals("gzip"))
in = new GZIPInputStream(conn.getInputStream());
if(conn.getContentEncoding().equals("deflate"))
in = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
// 從網頁輸入流列印內容到螢幕
BufferedReader bin = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String s = null;
while((s=bin.readLine())!=null){
System.out.println(s);
}
bin.close();
how to decode web content in gzip or deflate format using Java API?
訂閱:
張貼留言 (Atom)
Installing Code::Blocks on Windows for APCS Preparation
APCS 為大學程式設計先修檢測 (Advanced Placement Computer Science),其檢測等級可供大學個人申請入學時,比對是否符合各電腦相關科系APCS組申請資格之用。其中,針對 C 及 C++ 程式檢測者,考場提供 Linux 環境的輕量級 Code...
沒有留言:
張貼留言