Java活用生活

ログイン

オンライン状況

オンラインユーザー1人
ログインユーザー0人
登録ユーザー2人

カウンタ

COUNTER335478

日誌

Web Master >> 記事詳細
2023/01/05

HTTPで画像をダウンロード

固定リンク | by:aramaki
HTTPで画像をダウンロード
-----------------------------------------

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){

}
}

}
23:35 | 投票する | 投票数(0) | コメント(0)
Copyright © Java活用生活 All Rights Reserved .