1. 程式人生 > >httpclient封裝工具類

httpclient封裝工具類

前言

在日常開發中,我們經常需要通過http協議去呼叫網路內容,雖然java自身提供了net相關工具包,但是其靈活性和功能總是不如人意,於是有人專門搞出一個httpclient類庫,來方便進行Http操作。對於httpcore的原始碼研究,我們可能並沒有達到這種層次,在日常開發中也只是需要的時候,在網上百度一下,然後進行呼叫就行。在專案中對於這個工具類庫也許沒有進行很好的封裝。在哪裡使用就寫在哪些,很多地方用到,就在多個地方寫。反正是複製貼上,很方便,但是這樣就會導致專案中程式碼冗餘。所以這裡簡單的對httpcient的簡單操作封裝成一個工具類,統一放在專案的工具包中,在使用的時候直接從工具包中呼叫,不需要寫冗餘程式碼。

httpclient操作例項

首先需要在注意的一點是,這是基於httpclient4.5版本的,我們在使用的時候需要引入具體對應jar。下面是具體程式碼示例

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import
java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.config.RequestConfig; import
org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; /** * 基於 httpclient 4.5版本的 http工具類 * * @author 愛琴孩 * */ public class HttpClientTool { private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; // 採用靜態程式碼塊,初始化超時時間配置,再根據配置生成預設httpClient物件 static { RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } public static String doGet(String url, Map<String, String> params) { return doGet(url, params, CHARSET); } public static String doGetSSL(String url, Map<String, String> params) { return doGetSSL(url, params, CHARSET); } public static String doPost(String url, Map<String, String> params) throws IOException { return doPost(url, params, CHARSET); } /** * HTTP Get 獲取內容 * @param url 請求的url地址 ?之前的地址 * @param params 請求的引數 * @param charset 編碼格式 * @return 頁面內容 */ public static String doGet(String url, Map<String, String> params, String charset) { if (StringUtils.isBlank(url)) { return null; } try { if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } // 將請求引數和url進行拼接 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpGet.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** * HTTP Post 獲取內容 * @param url 請求的url地址 ?之前的地址 * @param params 請求的引數 * @param charset 編碼格式 * @return 頁面內容 * @throws IOException */ public static String doPost(String url, Map<String, String> params, String charset) throws IOException { if (StringUtils.isBlank(url)) { return null; } List<NameValuePair> pairs = null; if (params != null && !params.isEmpty()) { pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } } HttpPost httpPost = new HttpPost(url); if (pairs != null && pairs.size() > 0) { httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); } CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } catch (ParseException e) { e.printStackTrace(); } finally { if (response != null) response.close(); } return null; } /** * HTTPS Get 獲取內容 * @param url 請求的url地址 ?之前的地址 * @param params 請求的引數 * @param charset 編碼格式 * @return 頁面內容 */ public static String doGetSSL(String url, Map<String, String> params, String charset) { if (StringUtils.isBlank(url)) { return null; } try { if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpGet = new HttpGet(url); // https 注意這裡獲取https內容,使用了忽略證書的方式,當然還有其他的方式來獲取https內容 CloseableHttpClient httpsClient = HttpClientTool.createSSLClientDefault(); CloseableHttpResponse response = httpsClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpGet.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 這裡建立了忽略整數驗證的CloseableHttpClient物件 * @return */ public static CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); } }

總結

上面就是對於httpclient的簡單工具類,對於httpclient,還有很多知識點需要仔細研究,後面再和大家一起來總結學習!