2012年7月9日

HttpClient:透過get stream下載儲存檔案


 
使用 Apache HttpClient 4.2,
透過 http get 指令將回傳之 Stream 以檔案儲存。

圖片來源:http://ditchnet.org/httpclient/

程式如下:
 1 package werdna1222coldcodes.blogspot.com.demo.httpclient;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 import org.apache.commons.io.IOUtils;
10 import org.apache.http.HttpHost;
11 import org.apache.http.HttpResponse;
12 import org.apache.http.client.HttpClient;
13 import org.apache.http.client.methods.HttpGet;
14 import org.apache.http.conn.params.ConnRoutePNames;
15 import org.apache.http.impl.client.DefaultHttpClient;
16 
17 public class HttpGetDownloadFileDemo {
18 
19     public static void main(String[] args) {
20 
21         HttpClient client = new DefaultHttpClient();
22         HttpGet get = new HttpGet(
23             "http://www.apache.
24             org/dist/httpcomponents/httpclient/binary/httpcomponents-
25             client-4.2-bin.zip");
26         try {
27             
28             // if you need a proxy to connect to the internet, set it 
29             here.
30             HttpHost proxy = new HttpHost("your.proxy.com", 8080, 
31                              "http");
32             client.getParams().setParameter(ConnRoutePNames.
33                              DEFAULT_PROXY, proxy);
34 
35             // send get request
36             HttpResponse response = client.execute(get);
37             
38             // get http response stream and prepare the 
39             fileouputstream
40             InputStream in = response.getEntity().getContent();
41             BufferedInputStream bin = new BufferedInputStream(in);
42             OutputStream os = new FileOutputStream("D:/httpcomponents-
43                               client-4.2-bin.zip");
44             
45             Long time1 = System.currentTimeMillis();
46             // seems quicker when file is big, commons-io needed.
47             IOUtils.copy(bin, os);  // quicker
48             
49             // a little bit slower, 
50             // use entity.writeTo to copy the response stream to 
51             fileoutputstream.
52             // response.getEntity().writeTo(os);
53             Long time2 = System.currentTimeMillis();
54             System.out.println("Time spent: " + (double)(time2-time1)
55                                /1000 + " seconds.");
56 
57             bin.close();
58             in.close();
59             os.close();
60             client.getConnectionManager().shutdown();
61             
62         } catch (IOException e) {
63             e.printStackTrace();
64         } 
65     }
66 }

關鍵字:Apache, HttpClient, 4, 4.2, 下載, 檔案, 儲存, proxy, download, file,
參考資料:


更多精選推薦文章