public class DownImage {
private static final String targetContentType = "image/png";
private static final String InputData = "http://k.yimg.jp/images/top/sp2/cmn/logo-ns-131205.png";
public static void main(String[] args) {
InputStream inputStream=null;
OutputStream outputStream=null;
BufferedInputStream bufferedInputStream=null;
BufferedOutputStream bufferedOutputStream=null;
try{
// URL読込処理
URL url=new URL(InputData);
// inputStream=url.openConnection().getInputStream();
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
// 接続時にユーザー名やパスワードの入力を求められたとき、許可をするかどうか
connection.setAllowUserInteraction(false);// 許可しない
// キャッシュの使用を許可するか
connection.setUseCaches(false);// 許可しない
// プロトコルがリダイレクトに従うかどうか
connection.setInstanceFollowRedirects(true);// 従う
// HTTPに使用するメソッド
connection.setRequestMethod("GET");
// 接続
connection.connect();
// 結果コード
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
// コンテンツタイプ
if(connection.getContentType().equals(targetContentType)){
inputStream=connection.getInputStream();
}else{
throw new Exception("ContentType " + connection.getContentType());
}
}else{
throw new Exception("HTTP Status " + connection.getResponseCode());
}
bufferedInputStream=new BufferedInputStream(inputStream);
// 書込み処理
outputStream=new FileOutputStream("logo.png");
bufferedOutputStream=new BufferedOutputStream(outputStream);
int len;
byte[] b=new byte[2048];
while((len=bufferedInputStream.read(b))!=-1){
bufferedOutputStream.write(b,0,len);
bufferedOutputStream.flush();
}
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if(bufferedOutputStream!=null){
bufferedOutputStream.close();
}
if(bufferedInputStream!=null){
bufferedInputStream.close();
}
}catch(Exception e){
}
}