2012-09-22 49 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