1、HttpClient介紹html
雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,可是它沒有提供足夠的靈活性和其餘應用程序須要的功能。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。java
2、使用範例(如下版本4.3)編程
1,經過get方式,請求網頁內容。咱們首先建立httpclient對象,而後經過httpclient來執行http get方法,httpresponse得到服務端響應的全部內容,httpentity爲獲取的網頁消息體。數組
CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 以get方法執行請求 HttpGet httpGet = new HttpGet(「http://localhost/」); // 得到服務器響應的全部信息 CloseableHttpResponse responseGet = httpclient.execute(httpGet); try { System.out.println(responseGet.getStatusLine()); // 得到服務器響應的消息體(不包括http head) HttpEntity entity = responseGet.getEntity(); if (entity != null) { // 得到響應字符集編碼 ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); InputStream is = entity.getContent(); // 將inputstream轉化爲reader,並使用緩衝讀取,還可按行讀取內容 BufferedReader br = new BufferedReader( new InputStreamReader(is, charset)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } is.close(); } } finally { responseGet.close(); } } finally { httpclient.close(); }
2,經過post方式提交表單。瀏覽器可將登陸後的會話信息存儲到本地,登錄以後的每次請求都會自動向服務器發送cookie信息,幸虧的是httpclient亦可自動處理cookie信息。瀏覽器
CloseableHttpClient httpclient = HttpClients.createDefault(); // 以post方法發起登陸請求 String urlString = "http://localhost/llogin.do"; HttpPost httpPost = new HttpPost(urlString); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "admin")); nvps.add(new BasicNameValuePair("password", "admin")); // 添加post參數 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { // 狀態302的話,重定向,則沒法獲取響應消息體 System.out.println(response.getStatusLine()); // 得到服務器響應的消息體(不包括http head) HttpEntity entity = response.getEntity(); if (entity != null) { // 得到響應字符集編碼 ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); InputStream is = entity.getContent(); // 將inputstream轉化爲reader,並使用緩衝讀取,還可按行讀取內容 BufferedReader br = new BufferedReader( new InputStreamReader(is, charset)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } is.close(); } } finally { response.close(); }
3,重定向。httpclient默承認自動處理重定向請求,可是post方式需另外設置。服務器
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); CloseableHttpClient httpclient = HttpClients.custom() .setRedirectStrategy(redirectStrategy) .build(); HttpClientContext context = HttpClientContext.create(); try { // 以post方法執行登陸請求 HttpPost httpPost = new HttpPost(urlString); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "admin")); nvps.add(new BasicNameValuePair("password", "admin")); // 添加post參數 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost, context); try { // 狀態302的話,重定向,則沒法獲取響應消息體 System.out.println(response.getStatusLine()); // 得到服務器響應的消息體(不包括http head) HttpEntity entity = response.getEntity(); //輸出最終訪問地址 HttpHost targetHost = context.getTargetHost(); System.out.println(targetHost); List<URI> redirecLocations = context.getRedirectLocations(); URI location = URIUtils.resolve(httpPost.getURI(), targetHost, redirecLocations); System.out.println("Final HTTP location: " + location.toASCIIString()); if (entity != null) { // 得到響應字符集編碼 ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); InputStream is = entity.getContent(); // 將inputstream轉化爲reader,並使用緩衝讀取,還可按行讀取內容 BufferedReader br = new BufferedReader( new InputStreamReader(is, charset)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } is.close(); } } finally { response.close(); } } finally { httpclient.close(); }
4,利用httpclient,咱們能夠封裝一個方法,只要傳入httpclient對象和url地址,便可返回網頁內容。cookie
publicstatic String getHtml(HttpClient httpClient, String url) { // HttpClient主要用來執行http方法 CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 以get方法向服務端發起請求 HttpGet httpGet = new HttpGet(url); // 得到服務器響應的全部信息 CloseableHttpResponse responseGet = httpclient.execute(httpGet); try { // 得到服務器響應的消息體(不包括http head) HttpEntity entity = responseGet.getEntity(); if (entity != null) { // 得到響應字符集編碼 ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); InputStream is = entity.getContent(); //IOUtils是common-io提供的 String htmlString = IOUtils.toString(is); is.close(); return htmlString; } } finally { responseGet.close(); } } catch (Exception e) { e.printStackTrace(); } returnnull; }
另外,若訪問的是圖片,則可從輸入流中將內容存儲到byte數組中,如byte[] p_w_picpath = IOUtils.toByteArray(is),返回byte[]便可;若想下載保存到本地,可以使用IOUtils的方法:IOUtils.copy(is, new FileOutputStream(filename))。ide
這裏略提一下Apache-Commons-IO組件,它是對jdk中的io包進行拓展,讓咱們能夠更方便處理輸入輸出流和對文件的處理。工具
最後,要想學習熟悉httpclient,最好就是查看其官方文檔和它提供的範例,它的文檔和範例都很不錯,推薦閱讀。post
http://www.cnblogs.com/jianzhi/p/3362742.html