HTTP 請求工具類,GET請求帶引數,GET的map引數,POST請求帶引數,map引數,史上最全工具類
阿新 • • 發佈:2019-01-08
今天本來想在網上找一個HttpCline呼叫第三方藉口的方法,現在網上各種版本,自己在以前做過的專案裡找到了一個工具類,感覺挺方便的,裡面包括了get請求帶引數,get不帶引數,post帶引數,post不帶引數!
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.HttpClient; 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.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; 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.nio.charset.Charset; 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 請求工具類 */ public class HttpUtils { private static PoolingHttpClientConnectionManager connMgr; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 20000; 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(); } /** * 傳送 GET 請求(HTTP),不帶輸入資料 * * @param 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 * @param headers * 需要新增的httpheader引數 * @param params * @return */ public static String doGetHttp(String url, Map<String, String> headers, Map<String, Object> params) { HttpClient httpclient = new DefaultHttpClient(); 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)); i++; } apiUrl += param; String result = null; log("url: " + apiUrl); try { HttpGet httpGet = new HttpGet(apiUrl); // 新增http headers if (headers != null && headers.size() > 0) { for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } } HttpResponse response = httpclient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); log("code : " + statusCode); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); result = IOUtils.toString(instream, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * 傳送 SSL Get 請求(HTTPS),K-V形式 * * @param apiUrl * API介面URL * @param headers * @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 apiUrl = url; String httpStr = null; 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)); i++; } apiUrl += param; log("url: " + apiUrl); try { HttpGet httpGet = new HttpGet(apiUrl); httpGet.setConfig(requestConfig); // 新增http headers if (headers != null && headers.size() > 0) { for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } } response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); log("code : " + statusCode); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return 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; } /** * 傳送 POST 請求(HTTP),K-V形式 * * @param url * @param headers * 需要新增的httpheader引數 * @return */ public static String doPostByForm(String url, Map<String, String> headers, Map<String, Object> params) { if (url.startsWith("https://")) { return doPostSSL(url, headers, params); } else { return doPostHttp(url, headers, params); } } /** * 傳送 POST 請求(HTTP),JSON形式 * * @param url * @param headers * 需要新增的httpheader引數 * @return */ public static String doPostByJson(String url, Map<String, String> headers, Object json) { if (url.startsWith("https://")) { return doPostSSL(url, headers, json); } else { return doPostHttp(url, headers, json); } } /** * 傳送 POST 請求(HTTP),K-V形式 * * @param apiUrl * API介面URL * @param headers * 需要新增的httpheader引數 * @param params * 引數map * @return */ public static String doPostHttp(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; if (headers != null) { Set<String> keys = headers.keySet(); for (Iterator<String> i = keys.iterator(); i.hasNext();) { String key = (String) i.next(); httpPost.addHeader(key, headers.get(key)); } } try { httpPost.setConfig(requestConfig); 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, Charset.forName("UTF-8"))); response = httpClient.execute(httpPost); log(response.toString()); 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; } /** * 傳送 POST 請求(HTTP),JSON形式 * * @param apiUrl * @param headers * 需要新增的httpheader引數 * @param json * json物件 * @return */ public static String doPostHttp(String apiUrl, Map<String, String> headers, Object json) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; if (headers != null) { Set<String> keys = headers.keySet(); for (Iterator<String> i = keys.iterator(); i.hasNext();) { String key = (String) i.next(); httpPost.addHeader(key, headers.get(key)); } } try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); log(response.getStatusLine().getStatusCode() + ""); 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 doPostSSL(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; if (headers != null) { Set<String> keys = headers.keySet(); for (Iterator<String> i = keys.iterator(); i.hasNext();) { String key = (String) i.next(); httpPost.addHeader(key, headers.get(key)); } } try { httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList<NameValuePair>(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, Charset.forName("utf-8"))); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return 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 POST 請求(HTTPS),JSON形式 * * @param apiUrl * API介面URL * @param json * JSON物件 * @return */ public static String doPostSSL(String apiUrl, Map<String, String> headers, Object json) { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()) .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; if (headers != null) { Set<String> keys = headers.keySet(); for (Iterator<String> i = keys.iterator(); i.hasNext();) { String key = (String) i.next(); httpPost.addHeader(key, headers.get(key)); } } try { httpPost.setConfig(requestConfig); 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(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return 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() { // 建立TrustManager X509TrustManager 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的繼承者,但它們使用的是相同的SSLContext SSLContext ctx; try { ctx = SSLContext.getInstance("TLS"); // 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用 ctx.init(null, new TrustManager[] { xtm }, null); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx); return sslsf; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void log(String msg) { System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg); } /** * 測試方法 * * @param args */ public static void main(String[] args) throws Exception { } }
第三方藉口呼叫後就是解析資料了;
String轉為json可以使用
String PostString = HttpUtils.doPostByForm(url, headers, params);
JSONObject detail = JSONObject.parseObject(PostString);
String data = detail.get("data").toString;
.
(解析你的資料)
.