47

当我从带有 403 响应的 URL 获取数据时

is = conn.getInputStream();

它抛出一个 IOException 并且我无法获取响应数据。

但是当我使用firefox并直接访问该url时,ResponseCode仍然是403,但我可以获得html内容

4

5 回答 5

74

根据 javadocs,该HttpURLConnection.getErrorStream方法将返回InputStream可用于从错误条件(例如 404)中检索数据的方法。

于 2011-01-08T08:14:38.433 回答
22

的用法示例HttpURLConnection

String response = null;
try {
    URL url = new URL("http://google.com/pagedoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Hack to force HttpURLConnection to run the request
    // Otherwise getErrorStream always returns null
    connection.getResponseCode();
    InputStream stream = connection.getErrorStream();
    if (stream == null) {
        stream = connection.getInputStream();
    }
    // This is a try with resources, Java 7+ only
    // If you use Java 6 or less, use a finally block instead
    try (Scanner scanner = new Scanner(stream)) {
        scanner.useDelimiter("\\Z");
        response = scanner.next();
    }
} catch (MalformedURLException e) {
    // Replace this with your exception handling
    e.printStackTrace();
} catch (IOException e) {
    // Replace this with your exception handling
    e.printStackTrace();
}
于 2011-11-30T16:47:00.507 回答
15

尝试这样的事情:

try {
    String text = "url";
    URL url = new URL(text);
    URLConnection conn = url.openConnection();
    // fake request coming from browser
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;     rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    String f = in.readLine();
    in.close();
    System.out.println(f);
} catch (Exception e) {
    e.printStackTrace();
}
于 2011-01-08T10:19:40.097 回答
4

试试这个:

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getResponseCode() / 100 == 2 ? con.getInputStream() : con.getErrorStream()));

来源 https://stackoverflow.com/a/30712213/505623

于 2015-11-30T06:27:55.213 回答
0

I got the same error even after adding agent string. Finally after a days investigation figured out the issue. It is really weired if the url scheme start with "HTTPS" it results in error 403. It should be in lowercase ("https"). So make sure you call "url.toLowercase()" before opening the connection

于 2016-04-29T21:18:04.807 回答