47

403 応答のある URL からデータを取得すると

is = conn.getInputStream();

IOException がスローされ、応答データを取得できません。

しかし、Firefox を使用してその URL に直接アクセスすると、ResponseCode は 403 のままですが、html コンテンツを取得できます

4

5 に答える 5

74

HttpURLConnection.getErrorStreamメソッドは、javadocs によると、エラー状態 (404 など) からデータを取得するために使用できる を返しますInputStream

于 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

エージェント文字列を追加した後でも同じエラーが発生しました。最後に、数日間の調査の後、問題が判明しました。URL スキームが「HTTPS」で始まる場合、エラー 403 が発生するのは本当におかしなことです。小文字 (「https」) にする必要があります。したがって、接続を開く前に「url.toLowercase()」を呼び出すようにしてください。

于 2016-04-29T21:18:04.807 に答える