HttpURLConnection读取响应内容403错误

yav*_*ava 40 java http http-status-code-403

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

is = conn.getInputStream();
Run Code Online (Sandbox Code Playgroud)

它抛出IOException,我无法获取响应数据.

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

coo*_*ird 66

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

  • 不,它不会,因为函数的代码只包含'return null;' 线.(爪哇6,7) (3认同)
  • @Gangnus仔细阅读Javadoc:"如果没有连接连接,或者连接时服务器没有错误,或者服务器有错误但没有发送错误数据,则此方法将返回null.这是默认值".否则(错误4xx),您将获得要读取的流. (2认同)
  • @Gangnus HttpURLConnection是*abstract*class.具体实现与Javadoc中的解释完全相同. (2认同)

qwe*_*guy 20

用法示例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();
}
Run Code Online (Sandbox Code Playgroud)


Inf*_*ity 13

尝试这样的事情:

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();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试这个:

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getResponseCode() / 100 == 2 ? con.getInputStream() : con.getErrorStream()));
Run Code Online (Sandbox Code Playgroud)

来源 /sf/answers/2149854941/