我正在使用java的下载管理器
我的下载管理器正常工作,有一些下载链接
如果复制某个网站中提供的下载链接并在我的downloader
中使用它会产生不适当的结果
主要问题是下载文件的实际URL
当我直接在chrome中下载该文件时,我看到的Chrome链接使用的链接与我从网站复制的链接不同
我复制的URL
实际上重定向到其他URL
,这是实际的下载链接
如何解决此问题,以便downloader
正常工作。
我正在使用以下代码,但它也无效。
private HttpURLConnection checkForRedirect(URL url) throws IOException{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
redirect = true;
}
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
return conn;
}
我传递的网址是 https://class.coursera.org/pythonlearn-003/lecture/download.mp4?lecture_id=19 ,我希望重定向的网址 https://d28rh4a8wq0iu5.cloudfront.net/pythonlearn/recoded_videos/PY4INF-09-Dictionaries.1e3176607c9b11e3a3ad737af77ccaf6.mp4?response-content-type=application%2Foctet-stream&a=1&response-content-disposition=attachment%3B%20filename%3D%2211%2520-%25201%2520-%2520Chapter%25209%2520-%2520Dictionaries%2520%252837%253A38%2529.mp4%22%3B%20filename%2A%3DUTF-8%27%2711%2520-%25201%2520-%2520Chapter%25209%2520-%2520Dictionaries%2520%252837%253A38%2529.mp4