【问题标题】:How to download protected web page using Java如何使用 Java 下载受保护的网页
【发布时间】:2012-09-14 13:39:24
【问题描述】:

我们有一个任务,设计一个可以下载任何网页源代码的类。但是当我尝试测试我的代码并获取像http://anidb.net/perl-bin/animedb.pl?show=main 这样的页面时 - 没有任何效果。

这样的标准代码会失败:

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ø%È_äÖá__æ©A@,4x„ж_ëɃ?

我已经尝试了所有方法:cookie、头文件,但似乎没有任何效果。如果您对我有一些提示,我将不胜感激。

【问题讨论】:

  • 这无论如何都不会考虑字符编码。使用图书馆。

标签: java security download automation webpage


【解决方案1】:

编写 http 客户端,您必须考虑 gzip 编码以及分块传输。最好使用库来下载网页。

试试这样的: http://code.google.com/p/google-http-java-client/

【讨论】:

    【解决方案2】:

    您在问题中提到的网站似乎没有遵守“接受”请求标头,也没有正确设置“内容编码”响应标头,我认为这是不正确的。

    无论如何,您也可以使用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);
    }
    

    【讨论】:

    • 都是关于 gzip 的。我应该使用 java.util.zip.GZIPInputStream。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2015-02-07
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多