Java从网站下载文件

时间:2014-05-28 01:18:34

标签: java download torrent

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

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

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

2 个答案:

答案 0 :(得分:1)

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

收到的响应是压缩文件,处理解压缩文件的响应。 在给定的情况下,this(response.getEntity()。getContentEncoding())的输出是gzip。 我尝试将下载文件的扩展名更改为.zip,并且我能够在其中查看torrent文件。

答案 1 :(得分:-1)

如果你想下载一个文件。你可以使用HttpClient,这个pakage来自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();
    }
}