Java 实现Https访问工具类 跳过ssl证书验证
生活随笔
收集整理的這篇文章主要介紹了
Java 实现Https访问工具类 跳过ssl证书验证
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.70</version></dependency>
使用jdk自帶
package com.gblfy;import com.alibaba.fastjson.JSONObject;import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map;/*** Http請求* @author mszhou**/ public class HttpsUtils {private static final int TIMEOUT = 45000;public static final String ENCODING = "UTF-8";/*** 創建HTTP連接** @param url* 地址* @param method* 方法* @param headerParameters* 頭信息* @param body* 請求內容* @return* @throws Exception*/private static HttpURLConnection createConnection(String url,String method, Map<String, String> headerParameters, String body)throws Exception {URL Url = new URL(url);trustAllHttpsCertificates();HttpURLConnection httpConnection = (HttpURLConnection) Url.openConnection();// 設置請求時間httpConnection.setConnectTimeout(TIMEOUT);// 設置 headerif (headerParameters != null) {Iterator<String> iteratorHeader = headerParameters.keySet().iterator();while (iteratorHeader.hasNext()) {String key = iteratorHeader.next();httpConnection.setRequestProperty(key,headerParameters.get(key));}}httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + ENCODING);// 設置請求方法httpConnection.setRequestMethod(method);httpConnection.setDoOutput(true);httpConnection.setDoInput(true);// 寫query數據流if (!(body == null || body.trim().equals(""))) {OutputStream writer = httpConnection.getOutputStream();try {writer.write(body.getBytes(ENCODING));} finally {if (writer != null) {writer.flush();writer.close();}}}// 請求結果int responseCode = httpConnection.getResponseCode();if (responseCode != 200) {throw new Exception(responseCode+ ":"+ inputStream2String(httpConnection.getErrorStream(),ENCODING));}return httpConnection;}/*** POST請求* @param address 請求地址* @param headerParameters 參數* @param body* @return* @throws Exception*/public static String post(String address,Map<String, String> headerParameters, String body) throws Exception {return proxyHttpRequest(address, "POST", null,getRequestBody(headerParameters));}/*** GET請求* @param address* @param headerParameters* @param body* @return* @throws Exception*/public static String get(String address,Map<String, String> headerParameters, String body) throws Exception {return proxyHttpRequest(address + "?"+ getRequestBody(headerParameters), "GET", null, null);}/*** 讀取網絡文件* @param address* @param headerParameters* @param body* @param file* @return* @throws Exception*/public static String getFile(String address,Map<String, String> headerParameters, File file) throws Exception {String result = "fail";HttpURLConnection httpConnection = null;try {httpConnection = createConnection(address, "POST", null,getRequestBody(headerParameters));result = readInputStream(httpConnection.getInputStream(), file);} catch (Exception e) {throw e;} finally {if (httpConnection != null) {httpConnection.disconnect();}}return result;}public static byte[] getFileByte(String address,Map<String, String> headerParameters) throws Exception {byte[] result = null;HttpURLConnection httpConnection = null;try {httpConnection = createConnection(address, "POST", null,getRequestBody(headerParameters));result = readInputStreamToByte(httpConnection.getInputStream());} catch (Exception e) {throw e;} finally {if (httpConnection != null) {httpConnection.disconnect();}}return result;}/*** 讀取文件流* @param in* @return* @throws Exception*/public static String readInputStream(InputStream in, File file)throws Exception {FileOutputStream out = null;ByteArrayOutputStream output = null;try {output = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = in.read(buffer)) != -1) {output.write(buffer, 0, len);}out = new FileOutputStream(file);out.write(output.toByteArray());} catch (Exception e) {throw e;} finally {if (output != null) {output.close();}if (out != null) {out.close();}}return "success";}public static byte[] readInputStreamToByte(InputStream in) throws Exception {FileOutputStream out = null;ByteArrayOutputStream output = null;byte[] byteFile = null;try {output = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = in.read(buffer)) != -1) {output.write(buffer, 0, len);}byteFile = output.toByteArray();} catch (Exception e) {throw e;} finally {if (output != null) {output.close();}if (out != null) {out.close();}}return byteFile;}/*** HTTP請求** @param address* 地址* @param method* 方法* @param headerParameters* 頭信息* @param body* 請求內容* @return* @throws Exception*/public static String proxyHttpRequest(String address, String method,Map<String, String> headerParameters, String body) throws Exception {String result = null;HttpURLConnection httpConnection = null;try {httpConnection = createConnection(address, method,headerParameters, body);String encoding = "UTF-8";if (httpConnection.getContentType() != null&& httpConnection.getContentType().indexOf("charset=") >= 0) {encoding = httpConnection.getContentType().substring(httpConnection.getContentType().indexOf("charset=") + 8);}result = inputStream2String(httpConnection.getInputStream(),encoding);// logger.info("HTTPproxy response: {},{}", address,// result.toString());} catch (Exception e) {// logger.info("HTTPproxy error: {}", e.getMessage());throw e;} finally {if (httpConnection != null) {httpConnection.disconnect();}}return result;}/*** 將參數化為 body* @param params* @return*/public static String getRequestBody(Map<String, String> params) {return getRequestBody(params, true);}/*** 將參數化為 body* @param params* @return*/public static String getRequestBody(Map<String, String> params,boolean urlEncode) {StringBuilder body = new StringBuilder();Iterator<String> iteratorHeader = params.keySet().iterator();while (iteratorHeader.hasNext()) {String key = iteratorHeader.next();String value = params.get(key);if (urlEncode) {try {body.append(key + "=" + URLEncoder.encode(value, ENCODING)+ "&");} catch (UnsupportedEncodingException e) {// e.printStackTrace();}} else {body.append(key + "=" + value + "&");}}if (body.length() == 0) {return "";}return body.substring(0, body.length() - 1);}/*** 讀取inputStream 到 string* @param input* @param encoding* @return* @throws IOException*/private static String inputStream2String(InputStream input, String encoding)throws IOException {BufferedReader reader = new BufferedReader(new InputStreamReader(input,encoding));StringBuilder result = new StringBuilder();String temp = null;while ((temp = reader.readLine()) != null) {result.append(temp);}return result.toString();}/*** 設置 https 請求* @throws Exception*/private static void trustAllHttpsCertificates() throws Exception {HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {public boolean verify(String str, SSLSession session) {return true;}});javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];javax.net.ssl.TrustManager tm = new miTM();trustAllCerts[0] = tm;javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, null);javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());}//設置 https 請求證書static class miTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {return true;}public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {return true;}public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)throws java.security.cert.CertificateException {return;}public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)throws java.security.cert.CertificateException {return;}}//====================================================================//============================= 測試調用 ============================//====================================================================public static void main(String[] args) {try {//請求地址(我這里測試使用淘寶提供的手機號碼信息查詢的接口)String address = "https://192.168.13.81:8443/hound-api/api/v1/acc/auth/api/elastic/save_indexName";//請求參數Map<String, String> params = new HashMap<String, String>();params.put("indexName", "ppppsss");//這是該接口需要的參數params.put("userId", "317");//這是該接口需要的參數// 調用 get 請求String res = get(address, params, null);System.out.println(res);//打印返回參數res = res.substring(res.indexOf("{"));//截取JSONObject result = JSONObject.parseObject(res);//轉JSONSystem.out.println(result.toString());//打印} catch (Exception e) {// TODO 異常e.printStackTrace();}}}總結
以上是生活随笔為你收集整理的Java 实现Https访问工具类 跳过ssl证书验证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据加载约定表模型变更_08
- 下一篇: Java各个类型转化