Webからダウンロードして保存する DefaultHttpClientの使用例

    // ダウンロードして保存
    private void FileDownload(String uri,String filePath) throws IOException, URISyntaxException {
        int responseCode = 0;
        int BUFFER_SIZE = 10240;
        
        URI url = new URI(uri);

        HttpClient hClient = new DefaultHttpClient();
        HttpGet hGet = new HttpGet();
        HttpResponse hResp = null;

        hClient.getParams().setParameter("http.connection.timeout", new Integer(15000));

        hGet.setURI(url);

        hResp = hClient.execute(hGet);

        responseCode = hResp.getStatusLine().getStatusCode();

        if (responseCode == HttpStatus.SC_OK) {
            File file = new File(filePath);
            file.getParentFile().mkdir();
            InputStream is = hResp.getEntity().getContent();
            BufferedInputStream in = new BufferedInputStream(is, BUFFER_SIZE);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file, false), BUFFER_SIZE);

            byte buf[] = new byte[BUFFER_SIZE];
            int size = -1;
            while((size = in.read(buf)) != -1) {
                out.write(buf, 0, size);
            }
            out.flush();

            out.close();
            in.close();
        }
        else if (responseCode == HttpStatus.SC_NOT_FOUND) {
            /* ダウンロードファイルが見つからない */
        }
        else if (responseCode == HttpStatus.SC_REQUEST_TIMEOUT) {
            /* コネクションタイムアウト */
        }
    }

関連記事

スポンサーリンク

COALESCE関数 NULL値でない最初の引数を返す

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る