Java通过magnet 连接下载torrent 文件代码示例
时间: 2023-06-12 07:02:37 浏览: 319
Java通过magnet连接下载torrent文件需要用到第三方库,比如BT种子下载器Transmission的Java API。
以下是一个简单的示例代码:
```java
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.URLInfo;
import com.github.axet.wget.info.ex.DownloadError;
import com.github.axet.wget.info.ex.DownloadInterruptedError;
import com.github.axet.wget.info.ex.DownloadMultipartError;
import com.github.axet.wget.info.ex.DownloadRetry;
import com.github.axet.wget.info.ex.DownloadSSLException;
import com.github.axet.wget.info.ex.DownloadTimeoutException;
import com.github.axet.wget.info.ex.DownloadVerificationException;
@RestController
public class TorrentDownloadController {
private static final Logger LOGGER = LoggerFactory.getLogger(TorrentDownloadController.class);
private static final String TRANSMISSION_API_VERSION = "v2.94";
private static final String TRANSMISSION_RPC_URI = "/transmission/rpc";
private static final String TRANSMISSION_RPC_URL = "http://localhost:9091" + TRANSMISSION_RPC_URI;
private static final String MAGNET_URI_PREFIX = "magnet:?xt=urn:btih:";
private static final int CONNECT_TIMEOUT = 10000;
private static final int SOCKET_TIMEOUT = 30000;
private static final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
static {
connectionManager.setMaxTotal(100);
connectionManager.setDefaultMaxPerRoute(20);
}
@GetMapping(value = "/download/{magnetUri}", produces = MediaType.APPLICATION_JSON_VALUE)
public JSONObject download(@PathVariable String magnetUri) throws Exception {
LOGGER.info("Downloading torrent from magnet URI: {}", magnetUri);
String torrentUrl = getTorrentUrlFromMagnetUri(magnetUri);
LOGGER.info("Torrent URL: {}", torrentUrl);
// Download torrent file
String torrentFilePath = downloadTorrentFile(torrentUrl);
LOGGER.info("Torrent file downloaded to: {}", torrentFilePath);
// Add torrent to Transmission
JSONObject addTorrentResponse = addTorrentToTransmission(torrentFilePath);
LOGGER.info("Add torrent response: {}", addTorrentResponse);
return addTorrentResponse;
}
private String getTorrentUrlFromMagnetUri(String magnetUri) throws Exception {
if (!magnetUri.startsWith(MAGNET_URI_PREFIX)) {
throw new IllegalArgumentException("Invalid magnet URI: " + magnetUri);
}
String hash = magnetUri.substring(MAGNET_URI_PREFIX.length());
String infoHash = hash.split("&")[0];
String infoUrl = "https://itorrents.org/torrent/" + infoHash + ".torrent";
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.setConnectionManagerShared(true)
.build();
HttpGet httpGet = new HttpGet(infoUrl);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed to get torrent file URL, HTTP error code: " + response.getStatusLine().getStatusCode());
}
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonResponse = new JSONObject(new JSONTokener(responseBody));
String torrentUrl = jsonResponse.getString("url");
return torrentUrl;
}
private String downloadTorrentFile(String torrentUrl) throws Exception {
URL url = new URL(torrentUrl);
URLInfo urlInfo = new URLInfo(url);
String fileName = urlInfo.getFile().substring(urlInfo.getFile().lastIndexOf('/') + 1);
WGet wGet = new WGet(url, fileName);
wGet.setConnectTimeout(CONNECT_TIMEOUT);
wGet.setReadTimeout(SOCKET_TIMEOUT);
try {
wGet.download();
} catch (DownloadRetry e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadTimeoutException e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadMultipartError e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadInterruptedError e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadVerificationException e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadSSLException e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
} catch (DownloadError e) {
LOGGER.error("Failed to download torrent file: {}", e.getMessage());
throw new RuntimeException(e);
}
return fileName;
}
private JSONObject addTorrentToTransmission(String torrentFilePath) throws Exception {
String addTorrentUrl = TRANSMISSION_RPC_URL + "/" + TRANSMISSION_API_VERSION + "/torrent-add";
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.setConnectionManagerShared(true)
.build();
HttpGet httpGet = new HttpGet(addTorrentUrl);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
String jsonRequest = "{\"method\":\"torrent-add\",\"arguments\":{\"paused\":false,\"download-dir\":\"/downloads\",\"filename\":\"" + torrentFilePath + "\"}}";
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("X-Transmission-Session-Id", "null");
httpGet.setEntity(IOUtils.toInputStream(jsonRequest));
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 409) {
String sessionHeader = response.getFirstHeader("X-Transmission-Session-Id").getValue();
httpGet.setHeader("X-Transmission-Session-Id", sessionHeader);
httpGet.setEntity(IOUtils.toInputStream(jsonRequest));
response = httpClient.execute(httpGet);
}
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonResponse = new JSONObject(new JSONTokener(responseBody));
return jsonResponse;
}
}
```
这个示例代码使用了Transmission的Java API来添加torrent文件到Transmission,如果你想使用其他BT下载工具或者其他BT下载库,你需要修改相应的代码。
阅读全文