【问题标题】:Publicly accessible URL throwing IOException可公开访问的 URL 引发 IOException
【发布时间】:2015-10-09 10:10:15
【问题描述】:

我想访问链接http://www.nation.co.ke/business/seedsofgold/Egg-imports-from-Uganda-hatch-big-losses-for-farmers/-/2301238/2897930/-/dpeqesz/-/index.html

该链接可公开访问,甚至可以使用 curl 加载

但在 Java 代码中它会抛出 Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.nation.co.ke/business/seedsofgold/Egg-imports-from-Uganda-hatch-big-losses-for-farmers/-/2301238/2897930/-/dpeqesz/-/index.html

这是代码:

/**
 * 
 * @param url the HTML page
 * @throws IOException
 */
public static String getPage(String url) throws IOException {
    URL u = new URL(url);
    URLConnection conn = u.openConnection();

    String mime = conn.getContentType();
    if( !StringUtils.containsIgnoreCase(mime, "text/html") ) {
        return null; // don't continue if not HTML
    }
    else {

        // read the response body, using BufferedReader for performance
        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()));
        int n = 0, totalRead = 0;
        char[] buf = new char[1024];
        StringBuilder content = new StringBuilder();

        // read until EOF or first 16384 characters
        while (totalRead < 16384 && (n = reader.read(buf, 0, buf.length)) != -1) {
            content.append(buf, 0, n);
            totalRead += n;
        }
        reader.close();

}

错误发生在:

       InputStream in = conn.getInputStream();

相同的代码适用于其他 URL。

【问题讨论】:

    标签: java io inputstream urlconnection


    【解决方案1】:

    尝试添加

    conn.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");
    

    URLConnection conn = u.openConnection(); 之后立即连接到您的连接。当没有设置正确的代理时,许多网站会阻止站点访问。

    【讨论】:

      【解决方案2】:

      如果您收到 HTTP 403 状态代码,则表示由于某种原因禁止访问该 URL 标识的资源。

      Web 服务器可能会返回 403 Forbidden HTTP 状态代码以响应客户端对网页或资源的请求,以表明可以访问并理解该请求,但拒绝采取任何进一步的操作。

      您可以参考HTTP 403 status code

      【讨论】:

      • 只有通过URLConnection访问时才会出现403错误。该页面在浏览器中正确加载,甚至通过curl。有关解决方案,请参阅@ScreamingTree 的回答
      • 你只需要添加 User-agent 标头。
      猜你喜欢
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2020-11-23
      • 1970-01-01
      • 2021-08-05
      • 2019-04-28
      相关资源
      最近更新 更多