[英]Downloading File, java.io.IOException: Server returned HTTP response code: 403 for URL
[英]Why server returns me the Response Code 403 for a valid file in java?
我想通過java獲取這個文件的Content Length
:
https://www.subf2m.co/subtitles/farsi_persian-text/SImp4fRrRnBK6j-u2RiPdXSsHSuGVCDLz4XZQLh05FnYmw92n7DZP6KqbHhwp6gfvrxazMManmskHql6va6XEfasUDxGevFRmkWJLjCzsCK50w1lwNajPoMGPTy9ebCC0&name=Q2FwdGFpbiBNYXJ2ZWwgRmFyc2lQZXJzaWFuIGhlYXJpbmcgaW1wYWlyZWQgc3VidGl0bGUgLSBTdWJmMm0gW3N1YmYybS5jb10uemlw
當我在Firefox
或Google Chrome
插入這個 url 時,它會下載一個文件。 但是當我想通過Java HttpsURlConnection
查看該文件的大小時,服務器向我返回Response Code 403
和Content Length -1
。 為什么會這樣? 謝謝
try {
System.out.println("program started -----------------------------------------");
String str_url = "https://www.subf2m.co/subtitles/farsi_persian-text/SImp4fRrRnBK6j-u2RiPdXSsHSuGVCDLz4XZQLh05FnYmw92n7DZP6KqbHhwp6gfvrxazMManmskHql6va6XEfasUDxGevFRmkWJLjCzsCK50w1lwNajPoMGPTy9ebCC0&name=Q2FwdGFpbiBNYXJ2ZWwgRmFyc2lQZXJzaWFuIGhlYXJpbmcgaW1wYWlyZWQgc3VidGl0bGUgLSBTdWJmMm0gW3N1YmYybS5jb10uemlw";
URL url = new URL(str_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setConnectTimeout(150000);
con.setReadTimeout(150000);
con.setRequestMethod("HEAD");
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Accept-Encoding", "identity");
con.setRequestProperty("connection", "close");
con.connect();
System.out.println("responseCode: " + con.getResponseCode());
System.out.println("contentLength: " + con.getContentLength());
} catch (IOException e) {
System.out.println("error | " + e.toString());
e.printStackTrace();
}
輸出:
program started -----------------------------------------
responseCode: 403
contentLength: -1
默認的 Java 用戶代理被一些在線服務(最著名的是 Cloudflare)阻止。 您需要將User-Agent
標頭設置為其他內容。
con.setRequestProperty("User-Agent", "My-User-Agent");
根據我的經驗,只要不是默認設置,您將其設置為什么並不重要:
con.setRequestProperty("User-Agent", "aaa"); // works perfectly fine
編輯:看起來這個站點使用 Cloudflare 並啟用 DDoS 保護 - 您的代碼不會運行實際獲取文件內容所需的 JavaScript 挑戰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.