なんかダサいコードだけど。。。
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* QRコード作成
*/
public final class QrBuilder{
private String encode;
public enum QRtype{
PNG ("png")
,GIF ("gif")
,JPEG ("jpg")
,BitMap ("bmp")
;
private String type;
private QRtype(String type){
this.type = type;
}
protected String getType(){
return this.type;
}
}
public QrBuilder(){
this.encode = "UTF-8";
}
public QrBuilder(String encode){
this.encode = encode;
}
public void create(int size,QRtype qrtype,String data,File file){
StringBuilder sb = new StringBuilder();
sb.append("http://chart.apis.google.com/chart");
sb.append("?cht=qr");
sb.append("&chs=");
Integer ls = size;
sb.append(ls);
sb.append("x");
sb.append(ls);
sb.append("&chl=");
sb.append(data);
sb.append("&choe="+this.encode);
sb.append("&chof="+qrtype.getType());
try{
URL url = new URL(sb.toString());
HttpURLConnection uc = (HttpURLConnection)url.openConnection();
uc.setDoOutput(true);
uc.setReadTimeout(60000);
uc.setRequestMethod("GET");
Map<String,String> headerMap = new HashMap<String,String>();
headerMap.put("Content-Type","text/plain");
headerMap.put("Connection","close");
for(Iterator<String> it=headerMap.keySet().iterator();it.hasNext();){
String key = it.next();
uc.setRequestProperty(key,headerMap.get(key));
}
if (uc.getResponseCode() != 200){
throw new RuntimeException("response code "+uc.getResponseCode());
}
OutputStream out = new FileOutputStream(file);
InputStream in = uc.getInputStream();
byte[] buf = new byte[1024];
int n;
try{
while*1 >= 0){
out.write(buf, 0, n);
}
}finally{
out.close();
}
in.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
--------------------------------
QrBuilder b = new QrBuilder();
b.create(120,QRtype.PNG
,URLEncoder.encode("あいう","Shift_JIS")
,new File("c:/temp/a.png")
);
*1:n=in.read(buf