import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import javax.imageio.ImageIO;
public class ImageProvider {
private final String urlstr="認証がかかっているWebページのURL(画像のURL)";
private final String user="ユーザ名";
private final String pass="パスワード";
private URL url;
public ImageProvider(){
try {
Authentication auth= new Authentication(user,pass);
Authenticator.setDefault(auth);
url=new URL(urlstr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public BufferedImage getImage(){
BufferedImage image=null;
try {
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
InputStream is=con.getInputStream();
image=ImageIO.read(is);
is.close();
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
private class Authentication extends Authenticator{
private String user,pass;
public Authentication(String user,String pass){
this.user=user;
this.pass=pass;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,pass.toCharArray());
}
public String myGetRequestingPrompt(){
return super.getRequestingPrompt();
}
}
}
あとは,
new ImageProvider().getImage();
でBufferedImageが取得できるので,好きなように処理する!
# もっと良い方法があるんだろうな;;
参考:Java で HTTP クライアントを作ってみよう (3)
0 件のコメント:
コメントを投稿