AndroidでhttpリクエストとAndroidでファイル書き込みを組み合わせて
ダウンロードを行います。
(例外処理は端折ってます)
AIRIAさんのサイトを参考にしました。
http://gallop.ddo.jp/blog/airia/2010/09/android-7.html
処理手順:
// 0-1.レスポンスコード、バッファサイズの定義
int responseCode = 0;
int BUFFER_SIZE = 10240;
// 1.リクエストURLを用意する
String url = "http://wwww.google.co.jp/";
// 2.保存先を指定する。
String tmpFilePath = "/data/data/" + this.getPackageName()
+ "/test.html";
// 3.クライアント生成
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse response = null;
// 3-2.タイムアウトを設定する(軽いものならそんな重要じゃない)
client.getParams().setParameter("http.connection.timeout",
new Integer(15000));
// 4.リクエストを投げる
response = client.execute(method);
// 4-2.レスポンス確認
responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK) {//ステータス200(正常時)の処理}
// 5.ファイルオブジェクト生成
File file = new File(tmpFilePath);
// 6.ストリームオブジェクト生成
BufferedInputStream bin = null;
BufferedOutputStream out = null;
InputStream is = response.getEntity().getContent();
bin = new BufferedInputStream(is, BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(file,false), BUFFER_SIZE);
// 7.ストリーム取得
byte buf[] = new byte[BUFFER_SIZE];
int size = -1;
while ((size = bin.read(buf)) != -1) {
out.write(buf, 0, size);
}
// 8.ストリームクローズ
out.flush();
out.close();
bin.close();
ざーっと書きましたが、こんな感じでしょうか。
エミュレータで実行した場合は、DDMSの
Device>File Explorer
で保存したファイルを確認できます。