HTTP接続でファイルをダウンロード
- Android
-
2011-11-07 - 更新:2016-07-27
この記事は最終更新日から1年以上経過しています。
HTTP接続で簡単なテキストファイルのダウンロード
【必要なインポート宣言】
import java.io.*; import java.net.HttpURLConnection; import java.net.URL;
private String FileDownload(String uri)
{
HttpURLConnection http = null;
InputStream in = null;
BufferedReader reader = null;
try {
// 指定したURLにHTTP接続
URL url = new URL(uri);
http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.connect();
// データ取得
in = http.getInputStream();
// テキストデータ読み出し
String src = new String();
/* バイト単位で読み込む
byte[] buffer = new byte[1024];
int size;
while(true) {
size = in.read(buffer);
if(size <= 0) break;
src += new String(buffer);
}
in.close();*/
// 行毎に読み込む
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
src += line + "\n";
}
return src;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if(http != null) http.disconnect();
if(in != null) in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
この記事がお役に立ちましたらシェアお願いします
6,517 views




