https工具類和示例
阿新 • • 發佈:2019-02-14
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author dk * */ public class HttpUtils { private static Logger log = LoggerFactory.getLogger(HttpUtils.class); public static final SysConfig sysConfig = ApplicationContextUtil.getBean(SysConfig.class); private static final int BUFFER_SIZE = 1024; private static final String BOUNDARY = "----7d4a6d158c95fues7dkload8vdfsvhfdisvf04336w"; // 定義資料分隔線 public static final String CONTENT_TYPE_OF_APPLICATION_JSON = "application/json"; /** * 進行httpPost請求 * * @param postUrl * @param readTimeoutSeconds * @return */ public static String doHttpPost(String postUrl, int... readTimeoutSeconds) { return doHttpPost(postUrl, (String) null, readTimeoutSeconds); } /** * 進行httpPost請求 * * @param postUrl * @param postData * @param readTimeoutSeconds * @return */ public static String doHttpPost(String postUrl, String postData, int... readTimeoutSeconds) { return doHttpPost(postUrl, true, postData, readTimeoutSeconds); } /** * * 進行httpPost請求<br> * * @param postUrl * @param map * @param readTimeoutSeconds * @return */ public static String doHttpPost(String postUrl, Map<String, String> map, int... readTimeoutSeconds) { return doHttpPost(postUrl, map2KVPair(map), readTimeoutSeconds); } public static String doHttpPost(String postUrl, boolean usePOST, String postData, int... readTimeoutSeconds) { return doHttpPost(postUrl, usePOST, postData, null, null, readTimeoutSeconds); } public static String doHttpPost(String postUrl, boolean usePOST, String postData, Map<String, String> headers, String contentType, int... readTimeoutSeconds) { return doHttpPost(postUrl, usePOST, postData, headers, contentType, null, readTimeoutSeconds); } public static String doHttpPost(String postUrl, boolean usePOST, String postData, Map<String, String> headers, String contentType, KeyManager[] keyManagers, int... readTimeoutSeconds) { try { HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection(); conn.setDoInput(true); conn.setUseCaches(false); if (contentType != null && !contentType.equals("")) { conn.setRequestProperty("Content-Type", contentType); } conn.setRequestMethod(usePOST ? "POST" : "GET"); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("connection", "Keep-Alive"); if (headers != null && !headers.isEmpty()) { for (String key : headers.keySet()) { conn.setRequestProperty(key, headers.get(key)); } } if (readTimeoutSeconds != null && readTimeoutSeconds.length > 0) { conn.setReadTimeout(readTimeoutSeconds[0] * 1000); } boolean isHttpsRequest = postUrl.toLowerCase().startsWith("https"); // 對於https請求需要新增證書管理者 if (isHttpsRequest) { // 建立SSLContext物件,並使用我們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, tm, new java.security.SecureRandom()); // 從上述SSLContext物件中得到SSLSocketFactory物件 SSLSocketFactory ssf = sslContext.getSocketFactory(); // 設定請求方式(GET/POST) ((HttpsURLConnection) conn).setSSLSocketFactory(ssf); } if (postData != null) { conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(postData); out.flush(); out.close(); } else if (!usePOST) { conn.connect(); } // 將返回的輸入流轉換成字串 InputStream inputStream = conn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer buffer = new StringBuffer(); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } // 釋放資源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; // 斷開連線 conn.disconnect(); return buffer.toString(); } catch (MalformedURLException e) { log.error("doHttpPost MalformedURLException error:{}", e); } catch (KeyManagementException e) { log.error("doHttpPost KeyManagementException error:{}", e); } catch (NoSuchAlgorithmException e) { log.error("doHttpPost NoSuchAlgorithmException error:{}", e); } catch (IOException e) { log.error("doHttpPost IOException error:{}", e); } catch (Exception e) { log.error("doHttpPost Exception error:{}", e); } return null; } /** * 進行httpPost請求 * * @param postUrl * @param postData * @param readTimeoutSeconds * @return */ /* public static Map<String, String> doHttpPostGetJson(String postUrl, String postData, int... readTimeoutSeconds) { String resp = doHttpPost(postUrl, postData, readTimeoutSeconds); return parseJson(resp); } */ /** * 進行httpPost請求 * * @param postUrl * @param postData * @return */ /* public static Map<String, String> doHttpPostGetJson(String postUrl, Map<String, String> map, int... readTimeoutSeconds) { String resp = doHttpPost(postUrl, map, readTimeoutSeconds); return parseJson(resp); }*/ public static String doHttpPostForm(String postUrl, Map<String, String> paramMap, java.io.File[] files) throws Exception { if (paramMap == null) { paramMap = new HashMap<>(); } try { HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection(); boolean isHttpsRequest = postUrl.toLowerCase().startsWith("https"); if (isHttpsRequest) { // 建立SSLContext物件,並使用我們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext物件中得到SSLSocketFactory物件 SSLSocketFactory ssf = sslContext.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(ssf); } // 傳送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); conn.setChunkedStreamingMode(BUFFER_SIZE); // 每次填滿固定大小就輸出,檔案載入完不滿足固定大小,則會拋異常,不在本地緩衝 // conn.setFixedLengthStreamingMode(BUFFER_SIZE); conn.connect(); StringBuilder sb = new StringBuilder(); // 資料格式固定寫法 sb = sb.append("--"); sb = sb.append(BOUNDARY); sb = sb.append("\r\n"); for (String paramKey : paramMap.keySet()) { // 新增單個普通欄位--begin... sb = sb.append("Content-Disposition: form-data; name=\"" + paramKey + "\""); sb = sb.append("\r\n\r\n"); sb = sb.append(paramMap.get(paramKey)); sb = sb.append("\r\n"); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); // 新增單個普通欄位--end... } OutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(sb.toString().getBytes("UTF-8")); for (int i = 0; i < files.length; i++) { java.io.File file = files[i]; // 新增單個檔案欄位--begin... out.write(("Content-Disposition: form-data; name=\"" + "file_" + i + "\"; fileName=\"" + file.getName() + "\"\r\nContent-Type:application/octet-stream\r\n\r\n").getBytes("UTF-8")); try(FileInputStream fis = new FileInputStream(file.getAbsolutePath())){ // 空檔案 if (file.length() == 0) { out.write(0); } else { byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; while ((length = fis.read(buffer)) != -1) { out.write(buffer, 0, length); } } } byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(sysConfig.getCharacterset());// 定義最後資料分隔線 out.write(end_data); } if (files.length == 0) { byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(sysConfig.getCharacterset());// 定義最後資料分隔線 out.write(end_data); } out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = in.readLine()) != null) { buffer.append(line); } in.close(); return buffer.toString(); } catch (Exception e) { log.error("doPostForm error:{}", e); } return ""; } public static String getPostData(HttpServletRequest request) throws Exception { return getPostData(request, "UTF-8"); } public static String getPostData(HttpServletRequest request, String encoding) throws Exception { InputStream inputStream = request.getInputStream(); byte[] buffer = new byte[1024]; int length = 0; StringBuffer sb = new StringBuffer(); while ((length = inputStream.read(buffer)) > 0) { sb.append(new String(buffer, 0, length, encoding)); } return sb.toString(); } public static Map<String, List<String>> getHeaderFields(String postUrl, int... readTimeoutSeconds) { return getHeaderFields(postUrl, null, readTimeoutSeconds); } public static Map<String, List<String>> getHeaderFields(String postUrl, String postData, int... readTimeoutSeconds) { try { URLConnection conn = new URL(postUrl).openConnection(); if (postData != null) { conn.setDoOutput(true); conn.setRequestProperty("Pragma", "no-cache"); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("Content-Type", "text/xml"); if (readTimeoutSeconds != null && readTimeoutSeconds.length > 0) { conn.setReadTimeout(readTimeoutSeconds[0] * 1000); } OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), sysConfig.getCharacterset()); out.write(postData); out.flush(); out.close(); } return conn.getHeaderFields(); } catch (Exception e) { log.error("getHeaderFields error:{}", e); } return null; } /** * 從request中獲得引數Map,並返回可讀的Map * * @param request * @return */ @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" }) public static Map<String, String> getParameterMap(HttpServletRequest request) { Map returnMap = new HashMap(); Map properties = request.getParameterMap(); Iterator iterator = properties.entrySet().iterator(); String value = ""; while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Object valueObj = entry.getValue(); if (valueObj instanceof String[]) { String[] values = (String[]) valueObj; value = StringUtils.join(values, ","); } else { value = null != valueObj ? valueObj.toString() : ""; } returnMap.put((String) entry.getKey(), URLDecoder.decode(value)); } return returnMap; } /*public static <T> T getBeanFromRequest(HttpServletRequest request, Class<T> clazz) { return getBeanFromMap(getParameterMap(request), clazz); }*/ /*public static <T> T getBeanFromMap(Map<String, String> map, Class<T> clazz) { String gson = StringUtils.getGson(true).toJson(map); try { return StringUtils.getGson(true).fromJson(gson, clazz); } catch (Exception e) { log.error("getBeanFromMap error:{}", e); } return null; }*/ /** * 判斷請求是否來自ajax請求<br> * * @param request * @return */ /* public static boolean isAjaxRequest(HttpServletRequest request) { return StringUtils.isNotNullOrEmpty(request.getHeader("X-Requested-With")); }*/ @SuppressWarnings("all") public static class IP { private final static String[] IP = { "127.0.0.1", "0:0:0:0:0:0:0:1", "unknown" }; public static String getRemoteIpAddr(HttpServletRequest request) { String ip = null; if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("X-Real-IP"); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("http_client_ip"); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getHeader("x-forwarded-for"); } // 如果是多級代理,那麼取第一個ip為客戶ip if (ip != null && ip.indexOf(",") != -1) { ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); } if (StringUtils.isEmpty(ip) || ArrayUtils.contains(IP, ip)) { ip = request.getRemoteAddr(); } return StringUtils.defaultIfEmpty(ip, request.getRemoteAddr()); } public static final String getLocalIpAddr() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.error("UnknownHostException error:{}", e); return IP[0]; } } } public static String map2KVPair(Map<String, String> map) { StringBuffer sb = new StringBuffer(); int i = 0; for (String k : map.keySet()) { if (i++ > 0) { sb.append("&"); } sb.append(k).append("=").append(map.get(k)); } return sb.toString(); } } class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
單元測試用例:
@Test public void testQuerySummaryOfAgent(){ Map<String,Object> map = new HashMap<>(); map.put("pageNo", 1); map.put("pageSize", 500); map.put("summaryDate", "2018-08"); map.put("queryType", "07"); String request = JsonUtil.objectToJson(map); System.out.println(request); String result = HttpUtils .doHttpPost(httpsurl, true, request, null, "application/json", 50000); }