【问题标题】:Java Downloading file from websiteJava 从网站下载文件
【发布时间】:2014-05-28 01:18:33
【问题描述】:

我尝试了两种不同的方法来实现这一点,第一种:

public class DownloadTest {

    public static void main(String[] args) {
        URL website;
        try {
            website = new URL("http://re.zoink.it/067c4cc99A");
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream("vaca.torrent");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (Exception e) {
            Logger.getLogger(DownloadTest.class.getName()).log(Level.SEVERE, null, e);
        }

    }
}

第二个:

public class DownloadTest2 {

    public static void main(String args[]) throws IOException
    {
        String Episode = "http://re.zoink.it/067c4cc99A";
        String Episode_save = "vaca.torrent";
        java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(Episode).openStream());
        java.io.FileOutputStream fos = new java.io.FileOutputStream(Episode_save);
        java.io.BufferedOutputStream bout = new BufferedOutputStream(fos);
        byte data[] = new byte[1024];
        int read;
        while((read = in.read(data,0,1024))>=0)
        {
            bout.write(data, 0, read);
        }
        bout.close();
        in.close();
    }

}

如果您在浏览器中使用该链接,您将收到一个对话框来下载它。或者如果你尝试:view-source:http://re.zoink.it/067c4cc99A,你可以看到它是一个真正的torrent文件。

这两种方法都不适用于此链接(我得到了一个损坏的文件),但是它们确实适用于其他链接,例如http://www.bt-chat.com/download1.php?id=192039&type=torrent

我的问题是如何从第一个下载文件?

【问题讨论】:

  • 第二个示例中的代码似乎是做事的一般方式。您是否查看了以您结尾的文件,您有没有 diff'd 它与您手动下载时得到的一样?也许链接首先重定向到其他链接?
  • diff'd 是什么意思?我所知道的是大小是相同的(手动和使用java),但我通过java得到的那个是损坏的。 (我试图用一个共同的客户打开两者)
  • 有什么不同?你有完全相同的字节数吗?顺便说一句,您为什么使用缓冲输入和输出?

标签: java download torrent


【解决方案1】:

注意到当您使用 http 时无法访问此特定 url,而使用 https 我可以下载,将“http://re.zoink.it/067c4cc99A”更改为“https://re.zoink.it/067c4cc99A”。

收到的响应是压缩文件,处理响应解压文件。 在给定的情况下,这个 (response.getEntity().getContentEncoding()) 的输出是 gzip。 我尝试将下载文件的扩展名更改为 .zip,然后我可以看到其中的 torrent 文件。

【讨论】:

  • 进一步检查。您从该站点收到的响应是压缩格式。所以首先你需要解压它。尝试手动将扩展名更改为“.zip”,然后打开文件。您的实际文件将出现在其中。
  • 谢谢!还有一个问题:为什么我从浏览器下载的时候可以直接在我的bittorrent客户端打开,但是通过java下载的时候必须解压?
  • 所有浏览器都执行这个内置的解压过程。转换发生在浏览器上。许多网络服务器提供经过压缩的页面以节省网络带宽,然后由浏览器处理并提取此内容进行显示
【解决方案2】:

如果你想下载一个文件,你可以使用HttpClient,这个包来自apache 例如:

public void client(){
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://re.zoink.it/067c4cc99A");
    try {
        HttpResponse response = client.execute(request);
        if(response.getStatusLine().getStatusCode() == 200){
            InputStream is = response.getEntity().getContent();   //you can use this stream to download your file

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多