2011年2月23日水曜日

Web上のHTMLファイルをローカルに保存する

AndroidどころかJAVAが初めてなので、意外なところでよく躓く。
Web上のHTMLファイルをローカルに保存する、ということに関しても、色々ハマったので書いておく。


1. permissionの設定

res/AndroidManifest.xml に
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
の記述がないとインターネットに繋がらない。
書く場所は<manifest></manifest>の中。

2.  成功したコード

int responseCode = 0; 
HttpClient hClient = new DefaultHttpClient();  
HttpGet hGet = new HttpGet();  
HttpResponse hResp = null;  
          
hClient.getParams().setParameter("http.connection.timeout", new Integer(1500));  

String url="対象となるファイルのURL";
try {
URI uri = new URI(url);              
hGet.setURI(uri);  
hResp = hClient.execute(hGet);  
responseCode = hResp.getStatusLine().getStatusCode();  
             
if (responseCode == HttpStatus.SC_OK) {
 BufferedReader is = new BufferedReader((new InputStreamReader(hResp.getEntity().getContent(),"SJIS"))); 
 BufferedWriter os = new BufferedWriter((new OutputStreamWriter(new FileOutputStream(new File (Environment.getExternalStorageDirectory().getAbsolutePath()+"保存先のファイル名")),"SJIS")));
 String data;
 while((data = is.readLine()) != null) {
  os.write(data);
  os.write("\n");
 }
 os.flush();

} else if (responseCode == HttpStatus.SC_NOT_FOUND) {
} else if (responseCode == HttpStatus.SC_REQUEST_TIMEOUT) { 
}


}catch(Exception e){

}

3.  躓いたポイント
まず、 Copy A B のようなメソッドがないことに戸惑った。
ストリームの処理はまだよく分かっていない。
対称のコードがUNICODEなら"SJIS"は要らない。

WEB上のファイルへのアクセスは、2、3のサイトからサンプルコードをコピーして四苦八苦していたら、ある時突然つながった。どこのコードが元だったかはもう覚えていない。何がダメでなぜうまくいったのかはよく分からない。

Environment.getExternalStorageDirectory().getAbsolutePath() は要は/sdcard だが、一応格好付けてこう書いてみた。


#2011/3/4 ストリームの処理を少し書きなおした。

0 件のコメント:

コメントを投稿