简体   繁体   English

403 禁止用于 java 中的 url 而不是在浏览器中

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

I'm behind a corporate firewall, but i can paste the URL in my browser with and without my proxy settings enabled within the browser and can retrieve the data fine.我在公司防火墙后面,但我可以在浏览器中粘贴 URL,无论是否在浏览器中启用我的代理设置,并且可以很好地检索数据。 I just can't within java.我只是不能在java中。

Any ideas?有任何想法吗?

Code:代码:

 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;
}

Error:错误:

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)

Note: The '' portion is for anonymizing.注意:'' 部分用于匿名。

As you are receiving a "403: Forbidden" error, it means that your Java code can reach the URL, but it lacks something that is required to access it.当您收到“403: Forbidden”错误时,这意味着您的 Java 代码可以访问该 URL,但缺少访问它所需的某些内容。

In the browser, press F12 (developer/debug mode) and request the URL again.在浏览器中,按 F12(开发者/调试模式)并再次请求 URL。 Check the headers and cookies that are being sent.检查正在发送的标头和 cookie。 Most likely you will need to add one of these for you to be able to receive the content you need.您很可能需要添加其中之一才能接收所需的内容。

添加“User-Agent”标头为我修复了它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM