Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 HttpClient 實現檔案的上傳與下載

一、關於 HTTP

HTTP 大概是今日網際網路上使用最廣泛、也最重要的協議,越來越多 Java 應用需要直接透過 HTTP 存取網路資源。

JDK 的 java.net 包雖然提供了基本的 HTTP 存取能力,但對多數應用來說不夠豐富也不夠靈活。HttpClient 就是為了填補這個空缺而生:它提供高效、現代、功能完整的 HTTP 客戶端編程工具包,並支援當時最新的協議版本與建議。

一般我們用瀏覽器造訪 WEB 伺服器,看頁面、送表單、上下傳檔案。這些頁面有的公開、有的需登入、有的需要認證,還有的走 HTTPS 加密。瀏覽器處理這些情境都不是問題,但如果是不經瀏覽器要存取伺服器資源呢?這就是 HttpClient 的用武之地。

以下以本地上傳、下載檔案為例做個小 Demo。HttpClient 有兩套 API:一套是 org.apache.http 底下的新版本,另一套是 org.apache.commons.httpclient.HttpClient 的舊版本。

二、檔案上傳

上傳有兩種寫法:PostMethod 與 HttpPost,處理思路大同小異。PostMethod 用 FileBody 包裝檔案流,HttpPost 則用 FilePart;兩者在傳送檔案流的同時,都能一併帶上其他參數。

2.1 客戶端處理:PostMethod 方式

把檔案封裝進 FilePart 放入 Part 陣列,其他參數可用 setParameter 設定(此處以簡化方式呈現)。這裡的 HttpClient 是 org.apache.commons.httpclient.HttpClient。

public void upload(String localFile){
    File file = new File(localFile);
    PostMethod filePost = new PostMethod(URL_STR);
    HttpClient client = new HttpClient();
    try {
        // 通過以下方法可以模擬頁面參數提交
        filePost.setParameter("userName", userName);
        filePost.setParameter("passwd", passwd);

        Part[] parts = { new FilePart(file.getName(), file) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            System.out.println("上傳成功");
        } else {
            System.out.println("上傳失敗");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

收尾時別忘了 releaseConnection(),否則連線不會被釋放。

2.1.2 HttpPost 方式

寫法與上面類似,只是把 Part 陣列換成 HttpEntity、FilePart 換成 FileBody。此處的 HttpClient 來自 org.apache.http.client.methods。

public void upload(String localFile){
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {
        httpClient = HttpClients.createDefault();

        // 把一個普通參數和文件上傳給下面這個地址,是一個 servlet
        HttpPost httpPost = new HttpPost(URL_STR);

        // 把文件轉換成流對象 FileBody
        FileBody bin = new FileBody(new File(localFile));

        StringBody userName = new StringBody("Scott", ContentType.create(
            "text/plain", Consts.UTF_8));
        StringBody password = new StringBody("123456", ContentType.create(
            "text/plain", Consts.UTF_8));

        HttpEntity reqEntity = MultipartEntityBuilder.create()
            // 相當於 <input type="file" name="file"/>
            .addPart("file", bin)
            // 相當於 <input type="text" name="userName" value=userName>
            .addPart("userName", userName)
            .addPart("pass", password)
            .build();

        httpPost.setEntity(reqEntity);

        // 發起請求 並返回請求的響應
        response = httpClient.execute(httpPost);

        System.out.println("The response value of token:" + response.getFirstHeader("token"));

        // 獲取響應對象
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            // 打印響應長度
            System.out.println("Response content length: " + resEntity.getContentLength());
            // 打印響應內容
            System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
        }

        // 銷毀
        EntityUtils.consume(resEntity);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            if(response != null){
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(httpClient != null){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

更多內容見下一頁:https://www.linuxidc.com/Linux/2014-07/104303p2.htm

相關參考

  • Adroid 4.0 HttpURLConnection 拋異常解決方法 https://www.linuxidc.com/Linux/2013-03/81085.htm
  • node.js + Android(使用 HttpURLConnection 和 HttpClient)實現文件上傳 https://www.linuxidc.com/Linux/2012-02/53532p2.htm
  • 在 Android 上用 HttpURLConnection 獲取網頁內容 https://www.linuxidc.com/Linux/2011-08/41211.htm
Copyright © Linux教程網 All Rights Reserved