Java Jsoup下载torrent文件

时间:2018-07-26 20:21:12

标签: java download jsoup torrent

我遇到了问题,我想连接到该网站(https://ww2.yggtorrent.is)以下载torrent文件。我已经通过Jsoup开发了一种方法来连接到网站,该方法可以正常工作,但是当我尝试使用它来下载torrent文件时,网站返回“您必须连接才能下载文件”。

这是我要连接的代码:

Response res = Jsoup.connect("https://ww2.yggtorrent.is/user/login")
            .data("id", "<MyLogin>", "pass", "<MyPassword>")
            .method(Method.POST)
            .execute();

这是我下载文件的代码

Response resultImageResponse = Jsoup.connect("https://ww2.yggtorrent.is/engine/download_torrent?id=285633").cookies(cookies)
                                    .ignoreContentType(true).execute();

FileOutputStream out = (new FileOutputStream(new java.io.File("toto.torrent")));
out.write(resultImageResponse.bodyAsBytes());
out.close();

我已经测试了很多东西,但是现在我不知道了。

1 个答案:

答案 0 :(得分:1)

您没有在代码中向我们展示的唯一一件事就是从响应中获取Cookie。我希望您正确执行此操作,因为您使用它们进行了第二次请求。

此代码看起来像您的代码,但带有有关如何获取Cookie的示例。我还添加了引荐标头。它成功为我下载了该文件,并且utorrent正确识别了该文件:

    // logging in
    System.out.println("logging in...");
    Response res = Jsoup.connect("https://ww2.yggtorrent.is/user/login")
            .timeout(10000)
            .data("id", "<MyLogin>", "pass", "<MyPassword>")
            .method(Method.POST)
            .execute();

    // getting cookies from response
    Map<String, String> cookies = res.cookies();
    System.out.println("got cookies: " + cookies);

    // optional verification if logged in
    System.out.println(Jsoup.connect("https://ww2.yggtorrent.is").cookies(cookies).get()
            .select("#panel-btn").first().text());

    // connecting with cookies, it may be useful to provide referer as some servers expect it
    Response resultImageResponse = Jsoup.connect("https://ww2.yggtorrent.is/engine/download_torrent?id=285633")
            .referrer("https://ww2.yggtorrent.is/engine/download_torrent?id=285633")
            .cookies(cookies)
            .ignoreContentType(true)
            .execute();

    // saving file
    FileOutputStream out = (new FileOutputStream(new java.io.File("C:/toto.torrent")));
    out.write(resultImageResponse.bodyAsBytes());
    out.close();
    System.out.println("done");