2012-09-22 52 views
1

我們有一項任務,設計一個可以下載任何網頁源代碼的類。但是,當我嘗試測試我的代碼並獲取像http://anidb.net/perl-bin/animedb.pl?show=main這樣的頁面時 - 沒有任何工作。如何使用Java下載受保護的網頁

像這樣的標準代碼失敗:

import java.net.*; 
import java.io.*; 

public class URLReader { 
    public static void main(String[] args) throws Exception { 
     URL link = new URL("http://www.anidb.net/"); 
     BufferedReader in = new BufferedReader(
     new InputStreamReader(link.openStream())); 

     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
    } 
} 

這是我得到的結果是:

Šwq>²"¦§5´_ï__ÇUº=ôÙö?kŠ}~「bd`?l「Ïçz¢Çêõ>_"?j׉R「y}K¸\Ìc_DLÙªÏ_ 
    –óMm_¼_0」•ö°ËC_aí½sî¤ìÁS ‚>dC0ìs_–y¹ñ±ÏÝÜAø%È_äÖá__æ©[email protected],4x„Š¶_ëɃ? 

我已經嘗試了一切:餅乾,頭文件,但似乎沒有任何工作。如果你對我有一些暗示,我會很感激。

+3

看起來壓縮。 –

+0

無論如何,這並不會考慮字符編碼。使用圖書館。 – artbristol

回答

1

你在你的問題中提到的網站似乎並沒有兌現「Accept`請求頭,也沒有他們被設置‘正確內容編碼’響應頭,這我認爲是不正確的。

不管怎麼說,你也可以使用java.util.zip.GZipInputStream閱讀純文本格式的響應:

public static void main(String[] args) throws Exception 
{ 
    URL link = new URL("http://www.anidb.net/"); 
    HttpURLConnection con = (HttpURLConnection) link.openConnection(); 

    GZIPInputStream in = new GZIPInputStream(con.getInputStream()); 
    byte[] b = new byte[1024]; 
    StringBuilder content = new StringBuilder(); 
    while (in.read(b) > 0) 
    { 
     content.append(new String(b)); 
    } 
    System.out.println(content); 
} 
+0

這都是關於gzip的。我應該使用java.util.zip.GZIPInputStream。 謝謝。 – nikopol86