URL を指定し、Web ページの内容などをダウンロードしたい場合は、例えば Java では以下のように記述できます。
InputStream input = null;
try{
URL url = new URL("http://example.com/index.html");
input = url.openStream();
int len=0;
byte[] buf[] = new byte[1024];
while( (len = input.read(buf)) > 0 ){
System.out.println(new String(buf));
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
input.close();
}catch(IOException ignore){ }
}しかし、サーバによってはユーザエージェントなどを指定しないと、呼び出し元が不明とみなされ、403 (Forbidden)レスポンスコードが返りページの内容を取得できないことがあるようです。
この場合、例えば以下のように修正するとダウンロードできるようになります。
InputStream input = null;
try{
URL url = new URL("http://example.com/index.html");
URLConnection urlCon = url.openConnection();
urlCon.setRequestProperty("User-Agent","Mozilla/5.0");
input = urlCon.getInputStream();
// これ以降は、上記のプログラムの5行目以降と同じですここで気になった方もいると思いますが、実は openStream() はopenConnection().getInputStream() を呼び出しているだけで、エラーが発生するのは getInputStream() が呼び出されたときです。またユーザエージェントを付加するのは URLConnection のインスタンスに対してなので、上のような修正になります。


