歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用HttpClient實現文件的上傳下載

使用HttpClient實現文件的上傳下載

日期:2017/3/1 9:42:13   编辑:Linux編程

1 HTTP

HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程序需要直接通過 HTTP 協議來訪問網絡資源。

雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。

一般的情況下我們都是使用Chrome或者其他浏覽器來訪問一個WEB服務器,用來浏覽頁面查看信息或者提交一些數據、文件上傳下載等等。所訪問的這些頁面有的僅僅是一些普通的頁面,有的需要用戶登錄後方可使用,或者需要認證以及是一些通過加密方式傳輸,例如HTTPS。目前我們使用的浏覽器處理這些情況都不會構成問題。但是一旦我們有需求不通過浏覽器來訪問服務器的資源呢?那該怎麼辦呢?

下面以本地客戶端發起文件的上傳、下載為例做個小Demo。HttpClient有兩種形式,一種是org.apache.http下的,一種是org.apache.commons.httpclient.HttpClient。

2 文件上傳

文件上傳可以使用兩種方式實現,一種是PostMethod方式,一種是HttpPost方式。兩者的處理大同小異。PostMethod是使用FileBody將文件包裝流包裝起來,HttpPost是使用FilePart將文件流包裝起來。在傳遞文件流給服務端的時候,都可以同時傳遞其他的參數。

Adroid 4.0 HttpURLConnection拋異常解決方法 http://www.linuxidc.com/Linux/2013-03/81085.htm

node.js+Android(使用HttpURLConnection和HttpClient)實現文件上傳 http://www.linuxidc.com/Linux/2012-02/53532p2.htm

在Android上用HttpURLConnection獲取網頁內容 http://www.linuxidc.com/Linux/2011-08/41211.htm

2.1 客戶端處理

2.1.1 PostMethod方式

將文件封裝到FilePart中,放入Part數組,同時,其他參數可以放入StringPart中,這裡沒有寫,只是單純的將參數以setParameter的方式進行設置。此處的HttpClient是org.apache.commons.httpclient.HttpClient。

 1 public void upload(String localFile){
 2         File file = new File(localFile);
 3         PostMethod filePost = new PostMethod(URL_STR);
 4         HttpClient client = new HttpClient();
 5         
 6         try {
 7             // 通過以下方法可以模擬頁面參數提交
 8             filePost.setParameter("userName", userName);
 9             filePost.setParameter("passwd", passwd);
10 
11             Part[] parts = { new FilePart(file.getName(), file) };
12             filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
13             
14             client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
15             
16             int status = client.executeMethod(filePost);
17             if (status == HttpStatus.SC_OK) {
18                 System.out.println("上傳成功");
19             } else {
20                 System.out.println("上傳失敗");
21             }
22         } catch (Exception ex) {
23             ex.printStackTrace();
24         } finally {
25             filePost.releaseConnection();
26         }
27     }

記得搞完之後,要通過releaseConnection釋放連接。

2.1.2 HttpPost方式

這種方式,與上面類似,只不過變成了FileBody。上面的Part數組在這裡對應HttpEntity。此處的HttpClient是org.apache.http.client.methods下的。

 1 public void upload(String localFile){
 2         CloseableHttpClient httpClient = null;
 3         CloseableHttpResponse response = null;
 4         try {
 5             httpClient = HttpClients.createDefault();
 6             
 7             // 把一個普通參數和文件上傳給下面這個地址 是一個servlet
 8             HttpPost httpPost = new HttpPost(URL_STR);
 9             
10             // 把文件轉換成流對象FileBody
11             FileBody bin = new FileBody(new File(localFile));
12 
13             StringBody userName = new StringBody("Scott", ContentType.create(
14                     "text/plain", Consts.UTF_8));
15             StringBody password = new StringBody("123456", ContentType.create(
16                     "text/plain", Consts.UTF_8));
17 
18             HttpEntity reqEntity = MultipartEntityBuilder.create()
19                     // 相當於<input type="file" name="file"/>
20                     .addPart("file", bin)
21                     
22                     // 相當於<input type="text" name="userName" value=userName>
23                     .addPart("userName", userName)
24                     .addPart("pass", password)
25                     .build();
26 
27             httpPost.setEntity(reqEntity);
28 
29             // 發起請求 並返回請求的響應
30             response = httpClient.execute(httpPost);
31             
32             System.out.println("The response value of token:" + response.getFirstHeader("token"));
33                 
34             // 獲取響應對象
35             HttpEntity resEntity = response.getEntity();
36             if (resEntity != null) {
37                 // 打印響應長度
38                 System.out.println("Response content length: " + resEntity.getContentLength());
39                 // 打印響應內容
40                 System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
41             }
42             
43             // 銷毀
44             EntityUtils.consume(resEntity);
45         }catch (Exception e){
46             e.printStackTrace();
47         }finally {
48             try {
49                 if(response != null){
50                     response.close();
51                 }
52             } catch (IOException e) {
53                 e.printStackTrace();
54             }
55             
56             try {
57                 if(httpClient != null){
58                     httpClient.close();
59                 }
60             } catch (IOException e) {
61                 e.printStackTrace();
62             }
63         }
64     }

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-07/104303p2.htm

Copyright © Linux教程網 All Rights Reserved