2008年5月6日火曜日

Javaを使って,認証がかかったWebページから画像を取得する方法

タイトル通り,Javaを使って,認証がかかったWebページから画像を取得するのに手間取ったのでサンプルコードをメモ.

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)
 

2008年5月3日土曜日

javaアプレットの埋め込まれたページを見るとfirefoxがフリーズする

最近firefoxでJavaアプレットが埋め込まれたWebサイトを閲覧すると,firefoxが固まって動かなくなることが多発…

原因はjavaをアップデートした際にjavaの設定が変わってしまったためかも??

解決方法は以下のとおり.

1.コントロールパネルからJavaコントロールパネルを開く.
2.「基本」タブの「ネットワーク設定」で「直接接続」を選択する.

これで動くようになるはず!

2008年5月1日木曜日

LeopardでEPSONプリンタをサクサク使う

macbookのOSをLeopardにして以来ずっとプリンタ(EPSON LP-S5500)を使うときにダイアログがやたら遅いのが気になっていたが今まで放置してきた.

macbookのHDDの換装に伴ってすべての環境を再構築しているので,この際にダイアログの問題を解決することにした.

解決方法は非常に簡単だった!
Leopardに標準でEPSONプリンタのドライバが入っているが,これを使わずにEPSONのWebサイトから最新版のドライバをとってくる.(2008.5.1時点の最新版はlpx40bs.dmg)

これをインストールした後にプリンタを追加すると,ダイアログ表示がサクサクになった!