JAVA 傳送https請求
阿新 • • 發佈:2019-02-18
package com.linshang.mini.server.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HttpsURLConnection; 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 javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; public class HttpUtils { /** * 傳送https請求 * * @param path * @param method * @param body * @return */ public static String httpsRequestToString(String path, String method, String body) { if (path == null || method == null) { return null; } String response = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; HttpsURLConnection conn = null; try { // 建立SSLConrext物件,並使用我們指定的信任管理器初始化 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); TrustManager[] tm = { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; sslContext.init(null, tm, new java.security.SecureRandom()); // 從上面物件中得到SSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(path); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 設定請求方式(get|post) conn.setRequestMethod(method); // 有資料提交時 if (null != body) { OutputStream outputStream = conn.getOutputStream(); outputStream.write(body.getBytes("UTF-8")); outputStream.close(); } // 將返回的輸入流轉換成字串 inputStream = conn.getInputStream(); inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String str = null; StringBuffer buffer = new StringBuffer(); while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } response = buffer.toString(); } catch (Exception e) { } finally { if (conn != null) { conn.disconnect(); } try { bufferedReader.close(); inputStreamReader.close(); inputStream.close(); } catch (IOException execption) { } } return response; } }