【问题标题】:Server returned HTTP response code: 523 for URL: http服务器返回 HTTP 响应代码:523 用于 URL:http
【发布时间】:2015-04-08 08:22:03
【问题描述】:

我想爬一个网页,请求类型是post,但是我得到一个错误: java.io.IOException:服务器返回 HTTP 响应代码:523 用于 URL:http://

public static String readContentFromPost(String urlStr, String content) {
    URL url = null;
    HttpURLConnection con = null;
    StringBuffer sb = new StringBuffer();

    try {
        url = new URL(urlStr);
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setUseCaches(false);
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("Content-Type", "text/html;charset=utf-8");
        con.connect();

        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(content);

        out.flush();
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                con.getInputStream()));

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

【问题讨论】:

  • 你确定参数urlStr是正确的吗?

标签: java html http networking


【解决方案1】:

错误 523 没有任何标准含义:http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

所以这是您尝试抓取的服务器的专有错误...尝试联系网络管理员以了解其含义。

523 并不意味着 Unreachable origin... 它只意味着在 Cloudflare 中: https://support.cloudflare.com/hc/en-us/articles/200171946-Error-523-Origin-is-unreachable

在 Google 或 Wikipedia 等知名服务器上尝试您的代码,以了解其是否正常工作。

【讨论】:

  • 谢谢!我会尝试模拟浏览器获取数据
【解决方案2】:

抓取一个用javascript解决的网页也许可以使用selenium来模拟浏览器来获取数据。 硒:http://www.seleniumhq.org

首先创建一个maven项目并添加:

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.45.0</version>
    </dependency>

然后下载 ChromeDriver: http://chromedriver.storage.googleapis.com/index.html?path=2.14/

放到/usr/local/bin目录下

最后你可以抓取页面:

public static void testSelenium(String url) {
    // System.getProperties().setProperty("webdriver.chrome.driver","/Users/freezhan/IDE/tools/chromedriver");
    WebDriver webDriver = new ChromeDriver();

    webDriver.get(url);
    //WebElement webElement = webDriver.findElement(By.xpath("/html"));

    System.out.println(webDriver.getPageSource());

    webDriver.close();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多