日記を埋めるためだけのネタつぶし(6)

Dojaの通信クラス。
phpにアクセスして文字列を取得したり、ファイルにアクセスしてダウンロードしたりできる。


/*!
* @brief 通信クラス
*/
final public class CHttp implements Runnable
{
private boolean ret; //!< 現在の接続状態
private boolean dflg; //!< ダウンロードフラグ
private Exception e; //!< エラー
private HttpConnection hc; //!< コネクト
private String rstr; //!< 返す文字列
private byte[] buf; //!< ダウンロードしたバッファ
private int length; //!< データの長さ
private String url; //!< 接続先のURL

/*!
* @brief コンストラク
*/
public CHttp() {
ret = true;
dflg = false;
rstr = new String();
}
/*!
* @brief データの長さを取得
*
* @retval データの長さを返す
*/
public int getLength() {
return length;
}
/*!
* @brief 現在の接続状態
*
* @retval true:接続中
* @retval false:接続終了
*/
public boolean nowConnect() {
return ret;
}
/*!
* @brief エラーコードを取得
*
* @retval エラーコードを返す
* @retval エラーがない場合はnullを返す
*/
public Exception getError() {
return e;
}
/*!
* @brief 文字列を取得
*
* @retval 取得した文字列を返す
*/
public String getString() {
return rstr;
}
/*!
* @brief 接続開始
*
* @param url 接続先のURL
*/
public void connect(String url){
ret = true;
e = null;
dflg = false;
this.url = url;

(new Thread(this)).start();
}
/*!
* @brief 接続開始
*
* @param url 接続先のURL
* @param buf ダウンロードしたデータを受け取るバッファ
*/
public void connect(String url, byte[] buf){
ret = true;
e = null;
dflg = true;
this.url = url;
this.buf = buf;

(new Thread(this)).start();
}
/*!
* @brief 接続中
*/
public void run(){
InputStream is = null;
try {
hc = (HttpConnection)Connector.open(url, Connector.READ, true);
hc.setRequestMethod(HttpConnection.GET);
hc.connect();

if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
int size = (int)hc.getLength();
is = hc.openInputStream();
if (dflg == true) {
// データのダウンロード
length = is.read(buf);
if (length != size) {
// 取得した長さと実際にダウンロードした長さが違う場合は0を入れる
length = 0;
}
} else {
// 文字列取得
InputStreamReader reader = null;
StringBuffer stBuffer = new StringBuffer();
char[] readChars = new char[256];
int readLeng;

reader = new InputStreamReader(is);
while ( (readLeng = reader.read(readChars, 0, readChars.length) ) != -1){
//処理
stBuffer.append(readChars, 0, readLeng);
}
rstr = stBuffer.toString();
}
} else {
this.e = new Exception("ResponseCode:" + hc.getResponseCode());
var(e);
}
} catch(Exception e) {
this.e = e;
var(e);
} finally {
try {
is.close();
} catch(Exception e2) {
}
try {
hc.close();
} catch(Exception e2) {
}
}
ret = false;
}
};