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將文件流包裝起來。在傳遞文件流給服務端的時候,都可以同時傳遞其他的參數。
2.1 客戶端處理
2.1.1 PostMethod方式
將文件封裝到FilePart中,放入Part數組,同時,其他參數可以放入StringPart中,這里沒有寫,只是單純的將參數以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方式
這種方式,與上面類似,只不過變成了FileBody。上面的Part數組在這里對應HttpEntity。此處的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(); } } }
新聞熱點
疑難解答