簡體   English   中英

403 禁止用於 java 中的 url 而不是在瀏覽器中

[英]403 forbidden for url in java but not in browser

我在公司防火牆后面,但我可以在瀏覽器中粘貼 URL,無論是否在瀏覽器中啟用我的代理設置,並且可以很好地檢索數據。 我只是不能在java中。

有任何想法嗎?

代碼:

 private static String getURLToString(String strUrl) throws IOException {
    // LOG.debug("Calling URL: [" + strUrl + "]");
    String content = "";

    URLConnection connection = new URL(strUrl).openConnection();
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    connection.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));

    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        content += inputLine;
    }

    br.close();

    return content;
}

錯誤:

java.io.FileNotFoundException: Response: '403: Forbidden' for url: '<url here>'
    at weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:778)
    at weblogic.net.http.SOAPHttpURLConnection.getInputStream(SOAPHttpURLConnection.java:37)

注意:'' 部分用於匿名。

當您收到“403: Forbidden”錯誤時,這意味着您的 Java 代碼可以訪問該 URL,但缺少訪問它所需的某些內容。

在瀏覽器中,按 F12(開發者/調試模式)並再次請求 URL。 檢查正在發送的標頭和 cookie。 您很可能需要添加其中之一才能接收所需的內容。

添加“User-Agent”標頭為我修復了它:

connection.setRequestProperty("User-Agent", "Mozilla/5.0");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM