403 応答のある URL からデータを取得すると
is = conn.getInputStream();
IOException がスローされ、応答データを取得できません。
しかし、Firefox を使用してその URL に直接アクセスすると、ResponseCode は 403 のままですが、html コンテンツを取得できます
403 応答のある URL からデータを取得すると
is = conn.getInputStream();
IOException がスローされ、応答データを取得できません。
しかし、Firefox を使用してその URL に直接アクセスすると、ResponseCode は 403 のままですが、html コンテンツを取得できます
HttpURLConnection.getErrorStream
メソッドは、javadocs によると、エラー状態 (404 など) からデータを取得するために使用できる を返しますInputStream
。
の使用例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();
}
このようなことを試してください:
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();
}
これを試して:
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getResponseCode() / 100 == 2 ? con.getInputStream() : con.getErrorStream()));
エージェント文字列を追加した後でも同じエラーが発生しました。最後に、数日間の調査の後、問題が判明しました。URL スキームが「HTTPS」で始まる場合、エラー 403 が発生するのは本当におかしなことです。小文字 (「https」) にする必要があります。したがって、接続を開く前に「url.toLowercase()」を呼び出すようにしてください。