HttpUtils
轉載自 原文鏈接 link. 修改后如下:
居中的圖片:
import com.alibaba.fastjson.JSONObject; import com.google.gson.JsonObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; 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.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 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 javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.*;/*** HTTP 請求工具類*/ @Slf4j public class HttpUtils {private static PoolingHttpClientConnectionManager connMgr;private static RequestConfig requestConfig;private static final int MAX_TIMEOUT = 10000;static {// 設置連接池connMgr = new PoolingHttpClientConnectionManager();// 設置連接池大小connMgr.setMaxTotal(100);connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());RequestConfig.Builder configBuilder = RequestConfig.custom();// 設置連接超時configBuilder.setConnectTimeout(MAX_TIMEOUT);// 設置讀取超時configBuilder.setSocketTimeout(MAX_TIMEOUT);// 設置從連接池獲取連接實例的超時configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);// 在提交請求之前 測試連接是否可用configBuilder.setStaleConnectionCheckEnabled(true);requestConfig = configBuilder.build();}/*** @Description: 封裝請求頭信息* @param headers* @param httpPost* @return*/private static void packageHeader(Map<String, String> headers, HttpRequestBase httpPost) {if (headers != null) {Set<String> keys = headers.keySet();for (String key : keys) {httpPost.addHeader(key, headers.get(key));}}}/*** 發送 GET 請求* @param url API接口URL* @param headers 需要添加的httpheader參數* @return*/public static String doGet(String url, Map<String, String> headers, Map<String, Object> params) {if (url.startsWith("https://")) {return doGetSSL(url, headers, params);} else {return doGetHttp(url, headers, params);}}/*** 發送 GET 請求(HTTP),K-V形式* @param url API接口URL* @param headers 需要添加的httpheader參數* @param params 請求參數* @return*/public static String doGetHttp(String url, Map<String, String> headers, Map<String, Object> params) {//HttpClient httpclient = new DefaultHttpClient();CloseableHttpClient httpClient = HttpClients.createDefault(); // String apiUrl = url; // StringBuffer param = new StringBuffer(); // int i = 0; // for (String key : params.keySet()) { // if (i == 0) // param.append("?"); // else // param.append("&"); // param.append(key).append("=").append(params.get(key).toString()); // i++; // } // apiUrl += param;String result = null;try {//創建訪問的地址URIBuilder uriBuilder = new URIBuilder(url);if (params != null) {Set<Map.Entry<String, Object>> entrySet = params.entrySet();for (Map.Entry<String, Object> entry : entrySet) {uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());}}log("url: " + uriBuilder.build());HttpGet httpGet = new HttpGet(uriBuilder.build());httpGet.setConfig(requestConfig);// 添加http headerspackageHeader(headers,httpGet);HttpResponse response = httpClient.execute(httpGet);int statusCode = response.getStatusLine().getStatusCode();log("code : " + statusCode);HttpEntity entity = response.getEntity();if (statusCode == HttpStatus.SC_OK && entity != null) {InputStream instream = entity.getContent();result = IOUtils.toString(instream, StandardCharsets.UTF_8);}} catch (IOException | URISyntaxException e) {e.printStackTrace();}return result;}/*** 發送 SSL GET 請求(HTTPS),K-V形式* @param url API接口URL* @param headers 需要添加的httpheader參數* @param params 參數map* @return*/public static String doGetSSL(String url, Map<String, String> headers, Map<String, Object> params) {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();CloseableHttpResponse response = null;String httpStr = null;try {//創建訪問的地址URIBuilder uriBuilder = new URIBuilder(url);if (params != null) {Set<Map.Entry<String, Object>> entrySet = params.entrySet();for (Map.Entry<String, Object> entry : entrySet) {uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());}}HttpGet httpGet = new HttpGet(uriBuilder.build());log.debug("url:{}",uriBuilder.build());httpGet.setConfig(requestConfig);// 添加http headerspackageHeader(headers,httpGet);response = httpClient.execute(httpGet);int statusCode = response.getStatusLine().getStatusCode();log("code : " + statusCode);if (statusCode == HttpStatus.SC_OK && response.getEntity() != null) {httpStr = EntityUtils.toString(response.getEntity(), "utf-8");}} catch (Exception e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 發送 POST 請求,K-V形式* @param url API接口URL* @param headers 需要添加的httpheader參數* @return*/public static String doPostByForm(String url, Map<String, String> headers, Map<String, Object> params) {if (url.startsWith("https://")) {return doPostSSLKV(url, headers, params);} else {return doPostHttpKV(url, headers, params);}}/*** @Description: POST表單請求的參數封裝* @param params* @param httpPost* @return*/private static void packageParamsKV(Map<String, Object> params, HttpPost httpPost) {List<NameValuePair> pairList = new ArrayList<>(params.size());for (Map.Entry<String, Object> entry : params.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());pairList.add(pair);}httpPost.setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));}/*** 發送 POST 請求(HTTP),K-V形式* @param apiUrl API接口URL* @param headers 需要添加的httpheader參數* @param params 參數map* @return*/public static String doPostHttpKV(String apiUrl, Map<String, String> headers, Map<String, Object> params) {CloseableHttpClient httpClient = HttpClients.createDefault();String httpStr = null;HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;packageHeader(headers, httpPost);try {httpPost.setConfig(requestConfig);packageParamsKV(params, httpPost);response = httpClient.execute(httpPost);if (response != null && response.getStatusLine() != null && response.getEntity() != null) {log.debug("Content-Type:{}",response.getEntity().getContentType().getValue());HttpEntity entity = response.getEntity();httpStr = EntityUtils.toString(entity, "UTF-8");}} catch (IOException e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 發送 SSL POST 請求(HTTPS),K-V形式* @param apiUrl API接口URL* @param params 參數map* @return*/public static String doPostSSLKV(String apiUrl, Map<String, String> headers, Map<String, Object> params) {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;String httpStr = null;packageHeader(headers, httpPost);try {httpPost.setConfig(requestConfig);packageParamsKV(params, httpPost);response = httpClient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK && response.getEntity() != null) {httpStr = EntityUtils.toString(response.getEntity(), "utf-8");}} catch (Exception e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 發送 POST 請求,JSON形式* @param url API接口URL* @param headers 需要添加的httpheader參數* @return*/public static String doPostByJson(String url, Map<String, String> headers, Map<String,Object> json) {if (url.startsWith("https://")) {return doPostSSL(url, headers, json);} else {return doPostHttp(url, headers, json);}}private static void packageParamsJSON(Map<String, Object> json, HttpEntityEnclosingRequestBase httpMethod) {if (ParamUtils.isNotBlank(json)) {JSONObject finalJson = new JSONObject();for (Map.Entry<String, Object> entry : json.entrySet()) {finalJson.put(entry.getKey(),entry.getValue());}StringEntity stringEntity = new StringEntity(finalJson.toString(),"UTF-8"); // 解決中文亂碼問題stringEntity.setContentType("UTF-8");stringEntity.setContentType("application/json");httpMethod.setEntity(stringEntity);}}/*** 發送 POST 請求(HTTP),JSON形式* @param apiUrl API接口URL* @param headers 需要添加的httpheader參數* @param json json對象* @return*/public static String doPostHttp(String apiUrl, Map<String, String> headers, Map<String,Object> json) {CloseableHttpClient httpClient = HttpClients.createDefault();String httpStr = null;HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;packageHeader(headers, httpPost);try {httpPost.setConfig(requestConfig);packageParamsJSON(json,httpPost); // StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題 // stringEntity.setContentEncoding("UTF-8"); // stringEntity.setContentType("application/json"); // httpPost.setEntity(stringEntity);response = httpClient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();if (statusCode == HttpStatus.SC_OK && entity != null) {httpStr = EntityUtils.toString(entity, "UTF-8");}} catch (IOException e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 發送 SSL POST 請求(HTTPS),JSON形式* @param apiUrl API接口URL* @param json JSON對象* @return*/public static String doPostSSL(String apiUrl, Map<String, String> headers, Map<String,Object> json) {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(apiUrl);CloseableHttpResponse response = null;String httpStr = null;packageHeader(headers, httpPost);try {httpPost.setConfig(requestConfig); // StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題 // stringEntity.setContentEncoding("UTF-8"); // stringEntity.setContentType("application/json"); // httpPost.setEntity(stringEntity);packageParamsJSON(json,httpPost);response = httpClient.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();if (statusCode == HttpStatus.SC_OK && entity != null) {httpStr = EntityUtils.toString(entity, "utf-8");}} catch (Exception e) {e.printStackTrace();} finally {if (response != null) {try {EntityUtils.consume(response.getEntity());} catch (IOException e) {e.printStackTrace();}}}return httpStr;}/*** 創建SSL安全連接* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException*/private static SSLConnectionSocketFactory createSSLConnSocketFactory() {// 創建TrustManagerX509TrustManager xtm = new X509TrustManager() {public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return null;}};// TLS1.0與SSL3.0基本上沒有太大的差別,可粗略理解為TLS是SSL的繼承者,但它們使用的是相同的SSLContextSSLContext ctx;try {ctx = SSLContext.getInstance("TLS");// 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用ctx.init(null, new TrustManager[] { xtm }, null);return new SSLConnectionSocketFactory(ctx);} catch (NoSuchAlgorithmException | KeyManagementException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}public static void log(String msg) {System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t\t: " + msg);}/*** 測試方法* @param args*/public static void main(String[] args) {//todo} }總結
- 上一篇: 搭配实例的常见cmd命令+最简单bat病
- 下一篇: Markdown latex语法合集