【Java工具七】java使用HttpClient的post請求http、https示例
阿新 • • 發佈:2018-12-29
package com.xxx.utils; import com.google.gson.Gson; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; /** * http 請求介面 * * */ public class HttpUtils { public static final Gson gson = new Gson(); private static final String HTTP_PREFIX = "http://"; private static final String HTTPS_PREFIX = "https://"; private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); /** * 請求超時時間 */ public static final int CONNECTION_TIMEOUT_DEFAULT = 30000; /** * 響應超時時間 */ public static final int SOCKET_TIMEOUT_DEFAULT = 50000; /** * 無限超時時間 */ public static final int INFINITE_TIMEOUT = 0; /** * 接收/傳輸資料時使用的預設socket緩衝位元組大小 */ public static final int SOCKET_BUFFER_SIZE_DEFAULT = 81920; /** * 請求失敗後重新嘗試的次數 */ public static final int RETRY_COUNT_DEFAULT = 2; /** * 預設字符集 */ public static final String DEFAULT_CHARSET = "UTF-8"; public static final CloseableHttpClient httpClient = buildHttpClient(SOCKET_TIMEOUT_DEFAULT); public static final CloseableHttpClient httpClientNoTimeout = buildHttpClient(INFINITE_TIMEOUT); private static CloseableHttpClient buildHttpClient(int socketTimeout) { // 設定最大連線數和每個host的最大連線數 HttpClientBuilder httpClientBuilder = HttpClients.custom().setMaxConnTotal(2000).setMaxConnPerRoute(2000); // 內部預設使用 PoolingHttpClientConnectionManager 作為其連線管理器, 再次設定會覆蓋下面其它引數的設定 // httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager()); // 設定伺服器連線超時時間 及 伺服器響應超時時間 httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT_DEFAULT).setSocketTimeout(socketTimeout).build()); // 設定在關閉TCP連線時最大停留時間,是否禁用優化演算法延遲傳送資料 及 在非阻塞I/O情況下的伺服器響應時間 httpClientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoLinger(1500).setTcpNoDelay(true).setSoTimeout(socketTimeout).build()); // 設定接收/傳輸資料時的buffer大小,及預設字符集 httpClientBuilder.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(SOCKET_BUFFER_SIZE_DEFAULT).setCharset(Charset.forName(DEFAULT_CHARSET)).build()); // 設定失敗後重新嘗試訪問的處理器,不使用已經請求的連線 httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT_DEFAULT, false)); return httpClientBuilder.build(); } private static TrustManager myX509TrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { // TODO Auto-generated method stub } @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } }; public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray();// 網頁的二進位制資料 outStream.close(); inStream.close(); return data; } public static String getPostParam(Map<String, Object> params) throws Exception { StringBuffer buffer = new StringBuffer(); for (String key : params.keySet()) { String urlKey = URLEncoder.encode(key, "UTF-8"); String urlValue = URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8"); buffer.append(urlKey).append("=").append(urlValue).append("&"); } String paramStr = buffer.toString(); if (paramStr.endsWith("&") && paramStr.length() > 0) { paramStr = paramStr.substring(0, paramStr.length() - 1); } return paramStr; } public static String postForm(String url, Map<String, Object> params) throws Exception { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(params)); OutputStream out = null; if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) { url = HTTP_PREFIX + url; } URL localURL = new URL(url); URLConnection connection =null; if(url.toLowerCase().startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); out.write(getPostParam(params).getBytes()); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String postHttps(String url, String params) throws Exception { LOGGER.info("請求的url {},輸入引數 {}", url, new Gson().toJson(params)); OutputStream out = null; if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) { url = HTTP_PREFIX + url; } URL localURL = new URL(url); URLConnection connection =null; if(url.toLowerCase().startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); out.write(params.getBytes()); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String postForm(String url, String params) throws Exception { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(params)); OutputStream out = null; if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) { url = HTTP_PREFIX + url; } URL localURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) localURL.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); out.write(params.getBytes()); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); // String str = ""; return str; } public static String postGsonForm(String url, String params) throws Exception { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(params)); OutputStream out = null; URL localURL = new URL(url); HttpURLConnection connection = null; if(url.toLowerCase().startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestProperty("content-type", "application/json;charset=UTF-8"); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String postGsonFormForHeader (String url,String params,String accesstoken,String orgId,String appId) throws Exception { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(params)); OutputStream out = null; URL localURL = new URL(url); HttpURLConnection connection = null; if(url.toLowerCase().startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestProperty("content-type", "application/json;charset=UTF-8"); connection.setRequestProperty(accesstoken, accesstoken); connection.setRequestProperty(orgId, orgId); connection.setRequestProperty(appId, appId); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String postGsonForm(String url, String params, Map<String, Object> headerParams) throws Exception { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(params)); OutputStream out = null; URL localURL = new URL(url); HttpURLConnection connection = null; if(url.toLowerCase().startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestProperty("content-type", "application/json;charset=UTF-8"); connection.setDoOutput(true); connection.setDoInput(true); if (headerParams != null && !headerParams.isEmpty()) { for(Map.Entry<String, Object> headerParam:headerParams.entrySet()){ connection.setRequestProperty(headerParam.getKey(), headerParam.getValue().toString()); } } out = connection.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String getForm(String url, String params) throws Exception { url = url + "?" + params; URL localURL = new URL(url); HttpURLConnection connection = null; if(url.startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static String getForm(String url, Map<String, Object> params) throws Exception { url = url + "?" + getPostParam(params); URL localURL = new URL(url); HttpURLConnection connection = null; if(url.startsWith(HTTPS_PREFIX)){ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL requestUrl = new URL(url); HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection(); httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory()); connection=httpsConn; }else{ connection = (HttpURLConnection) localURL.openConnection(); } connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setUseCaches(false); InputStream inStream = connection.getInputStream(); String str = new String(readInputStream(inStream), "UTF-8"); return str; } public static Map<String, Object> getMap(String key, Object value) { Map<String, Object> result = new HashMap<String, Object>(); result.put(key, value); return result; } public static String post(String url, NameValuePair[] data) { LOGGER.info("請求的url {},輸入引數{}", url, new Gson().toJson(data)); String responseMsg = null; // 1.構造HttpClient的例項 HttpClient httpClient = new HttpClient(); httpClient.getParams().setContentCharset("UTF-8"); // 2.構造PostMethod的例項 PostMethod postMethod = new PostMethod(url); // 3.把引數值放入到PostMethod物件中 postMethod.setRequestBody(data); try { // 4.執行postMethod,呼叫http介面 httpClient.executeMethod(postMethod);// 200 // 5.讀取內容 responseMsg = postMethod.getResponseBodyAsString().trim(); // 6.處理返回的內容 } catch (HttpException e) { LOGGER.error(e.getMessage(),e); } catch (IOException e) { LOGGER.error(e.getMessage(),e); } finally { // 7.釋放連線 postMethod.releaseConnection(); } return responseMsg; } public static void main(String[] args) { try { Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("orgId", "5835"); String[] userIds = {"84544"}; paramsMap.put("userIds", userIds); String[] userNames = {"測試名片2"}; paramsMap.put("userNames", userNames); String[] userPhones = {"18611368266"}; paramsMap.put("userPhones", userPhones); Map<String, Object> headerParams = new HashMap<>(); headerParams.put("token", "4b55b10a8f454beacf8d9fd9b85f453a"); String params = JSONUtils.toJson(paramsMap); String url = "http://172.31.81.37:8080/CardManagerUI/usermanager/grantUserCard"; String rv = HttpUtils.postGsonForm(url, params,headerParams); System.out.println("rv:"+rv); } catch (Exception e) { e.printStackTrace(); } } }