HTTP請求工具類---請求引數放入paramter中
阿新 • • 發佈:2019-01-04
這裡我們將http請求引數放到paramter中(對方在獲取我們引數的時候 ,可以通過request.getparamter(key))來獲取;我們用到的是apache 的工具HttpClient。我們需要引入的包分別為:
這三個包可以從apache官網上下載,也可以從這裡下載:https://pan.baidu.com/s/1ejRsdC
下面我們就來實現下我們工具類的實現:
在這裡我測試過:如果我們將請求的引數寫入到流裡面我們是無法通request.getparamter(key) 來獲取我們傳遞的引數,只能從流裡面來讀取我們傳遞的引數字串。但是通過上述方式我們可以實現request.getparamter(key) 來獲取,也可以通過讀取流的方式獲取我們傳遞的引數序列。package com.zpl.util.http; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; 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.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.zpl.logs.LogUtil; public class HttpClient { private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000) .setConnectionRequestTimeout(15000).build(); private boolean checkTimeout = false; private static HttpClient instance = null; private HttpClient() { // test } public static HttpClient getInstance() { if (instance == null) { instance = new HttpClient(); } return instance; } /** * 傳送 post請求 * * @param httpUrl * 地址 */ public String sendHttpPost(String httpUrl) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost return sendHttpPost(httpPost); } /** * 傳送 post請求 * * @param httpUrl * 地址 * @param params * 引數(格式:key1=value1&key2=value2) */ public String sendHttpPost(String httpUrl, String params) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost try { // 設定引數 StringEntity stringEntity = new StringEntity(params, "UTF-8"); stringEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(stringEntity); } catch (Exception e) { LogUtil.error(e.getMessage()); } return sendHttpPost(httpPost); } /** * 傳送 post請求 * * @param httpUrl * 地址 * @param maps * 引數 */ public String sendHttpPost(String httpUrl, Map<String, String> maps) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost // 建立引數佇列 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) { LogUtil.error(e.getMessage()); } return sendHttpPost(httpPost); } /** * 傳送Post請求 * * @param httpPost * @return */ private String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立預設的httpClient例項. httpClient = HttpClients.createDefault(); if (this.checkTimeout) httpPost.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { LogUtil.error(e.getMessage()); } finally { try { // 關閉連線,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { LogUtil.error(e.getMessage()); } } return responseContent; } /** * 傳送 get請求 * * @param httpUrl */ public String sendHttpGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl);// 建立get請求 return sendHttpGet(httpGet); } /** * 傳送 get請求Https * * @param httpUrl */ public String sendHttpsGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl);// 建立get請求 return sendHttpsGet(httpGet); } /** * 傳送Get請求 * * @param httpPost * @return */ private String sendHttpGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立預設的httpClient例項. httpClient = HttpClients.createDefault(); if (this.checkTimeout) httpGet.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { LogUtil.error(e.getMessage()); } finally { try { // 關閉連線,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { LogUtil.error(e.getMessage()); } } return responseContent; } /** * 傳送Get請求Https * * @param httpPost * @return */ private String sendHttpsGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立預設的httpClient例項. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString())); DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build(); if (this.checkTimeout) httpGet.setConfig(requestConfig); // 執行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); // Ulog.error(e); } finally { try { // 關閉連線,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { LogUtil.error(e.getMessage()); } } return responseContent; } public String sendHttpsPost(String httpUrl, Map<String, String> maps) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost // 建立引數佇列 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) { e.printStackTrace(); // Ulog.error(e); } try { return sendHttpsPost(httpPost); } catch (Exception e) { throw new RuntimeException(e); } } private String sendHttpsPost(HttpPost httpPost) throws Exception { // 採用繞過驗證的方式處理https請求 SSLContext sslcontext = createIgnoreVerifySSL(); // 設定協議http和https對應的處理socket連結工廠的物件 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); // 建立自定義的httpclient物件 CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build(); // 執行請求操作,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); // 獲取結果實體 HttpEntity entity = response.getEntity(); String body = ""; if (entity != null) { // 按指定編碼轉換結果實體為String型別 body = EntityUtils.toString(entity, "UTF-8"); } EntityUtils.consume(entity); // 釋放連結 response.close(); return body; } /** * 繞過驗證 * * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException */ private SSLContext createIgnoreVerifySSL() throws Exception { SSLContext sc = SSLContext.getInstance("SSL"); // 實現一個X509TrustManager介面,用於繞過驗證,不用修改裡面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init(null, new TrustManager[] { trustManager }, null); return sc; } /** * 是否校驗超時時間 * * @return true:校驗<br> * false:不校驗(預設) */ public boolean isCheckTimeout() { return checkTimeout; } /** * 設定是否校驗超時時間 * * @param checkTimeout * true:校驗<br> * false:不校驗(預設) */ public void setCheckTimeout(boolean checkTimeout) { this.checkTimeout = checkTimeout; } }