国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 網(wǎng)站 > 幫助中心 > 正文

使用HttpClient實(shí)現(xiàn)文件的上傳下載方法

2024-07-09 22:41:11
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1 HTTP

HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來(lái)越多的 Java 應(yīng)用程序需要直接通過(guò) HTTP 協(xié)議來(lái)訪問(wèn)網(wǎng)絡(luò)資源。

雖然在 JDK 的 java.net 包中已經(jīng)提供了訪問(wèn) HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來(lái)說(shuō),JDK 庫(kù)本身提供的功能還不夠豐富和靈活。HttpClient 用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。

一般的情況下我們都是使用Chrome或者其他瀏覽器來(lái)訪問(wèn)一個(gè)WEB服務(wù)器,用來(lái)瀏覽頁(yè)面查看信息或者提交一些數(shù)據(jù)、文件上傳下載等等。所訪問(wèn)的這些頁(yè)面有的僅僅是一些普通的頁(yè)面,有的需要用戶登錄后方可使用,或者需要認(rèn)證以及是一些通過(guò)加密方式傳輸,例如HTTPS。目前我們使用的瀏覽器處理這些情況都不會(huì)構(gòu)成問(wèn)題。但是一旦我們有需求不通過(guò)瀏覽器來(lái)訪問(wèn)服務(wù)器的資源呢?那該怎么辦呢?

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

2 文件上傳

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

2.1 客戶端處理

2.1.1 PostMethod方式

將文件封裝到FilePart中,放入Part數(shù)組,同時(shí),其他參數(shù)可以放入StringPart中,這里沒(méi)有寫(xiě),只是單純的將參數(shù)以setParameter的方式進(jìn)行設(shè)置。此處的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 {      // 通過(guò)以下方法可以模擬頁(yè)面參數(shù)提交      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();    }  }

記得搞完之后,要通過(guò)releaseConnection釋放連接。

2.1.2 HttpPost方式

這種方式,與上面類似,只不過(guò)變成了FileBody。上面的Part數(shù)組在這里對(duì)應(yīng)HttpEntity。此處的HttpClient是org.apache.http.client.methods下的。

public void upload(String localFile){    CloseableHttpClient httpClient = null;    CloseableHttpResponse response = null;    try {      httpClient = HttpClients.createDefault();            // 把一個(gè)普通參數(shù)和文件上傳給下面這個(gè)地址 是一個(gè)servlet      HttpPost httpPost = new HttpPost(URL_STR);            // 把文件轉(zhuǎn)換成流對(duì)象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()          // 相當(dāng)于<input type="file" name="file"/>          .addPart("file", bin)                    // 相當(dāng)于<input type="text" name="userName" value=userName>          .addPart("userName", userName)          .addPart("pass", password)          .build();      httpPost.setEntity(reqEntity);      // 發(fā)起請(qǐng)求 并返回請(qǐng)求的響應(yīng)      response = httpClient.execute(httpPost);            System.out.println("The response value of token:" + response.getFirstHeader("token"));              // 獲取響應(yīng)對(duì)象      HttpEntity resEntity = response.getEntity();      if (resEntity != null) {        // 打印響應(yīng)長(zhǎng)度        System.out.println("Response content length: " + resEntity.getContentLength());        // 打印響應(yīng)內(nèi)容        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();      }    }  }
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 贺兰县| 高唐县| 靖宇县| 绥德县| 沛县| 临泽县| 京山县| 宁河县| 苍南县| 湘阴县| 嘉鱼县| 尉氏县| 深州市| 贵溪市| 霍州市| 泸水县| 始兴县| 深泽县| 青岛市| 民丰县| 石林| 牡丹江市| 萨嘎县| 平塘县| 库车县| 康马县| 沙洋县| 榕江县| 海盐县| 屯门区| 韶山市| 桓台县| 榆中县| 南宁市| 北川| 永安市| 桑植县| 保靖县| 吉安县| 社旗县| 绍兴市|