2010年4月26日月曜日

Server returned HTTP response code: 403 for URLに対して

このエントリーをはてなブックマークに追加
Javaです.

URLConnectionを使って,HTTPコネクションをはり,HTMLを取得する際,下記のように書く.

import java.io.*;
import java.net.*;

public class MyURLConnection {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/");
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


ただ,サイトによっては,
java.io.IOException: Server returned HTTP response code: 403 for URL:
というエラーが発生する.
そこで,下記のように,ヘッダを設定するとすんなり通る.

import java.io.*;
import java.net.*;

public class MyURLConnection {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
URLConnection conn = url.openConnection();
/////////////////////////////////////////////////////
conn.setRequestProperty("User-agent","Mozilla/5.0");
/////////////////////////////////////////////////////
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


これは,ヘッダが正しく設定されてないHTTPコネクションに対しては,サーバ側が受理しないことがあるため(よくわからないプログラムからアクセスされていると推測できる).
そこで,ヘッダを設定してあげると通る.

ということでいいのかな???