首页

通过java.security.cert/javax.net.ssl安全认证通道定义HttpsUtils工具类实现常用基于https协议数据请求处理代码示例

标签:java.security.cert,javax.net.ssl,安全认证通道,HttpsUtils,https工具类,https协议     发布时间:2018-08-05   

一、前言

关于通过javax.net.ssl.*、java.security.cert.X509Certificate安全通道证书类定义https安全认证通道工具类,进行基于https的数据get/post/JsonPost/HttpsGo/XmlPost/FormPost等操作,详情参见代码示例。

二、代码示例

import java.io.InputStream;@b@import java.io.OutputStream;@b@import java.net.HttpURLConnection;@b@import java.net.URL;@b@import java.net.URLEncoder;@b@import java.nio.charset.Charset;@b@import java.security.SecureRandom;@b@import java.security.cert.CertificateException;@b@import java.security.cert.X509Certificate;@b@import java.util.Arrays;@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@import javax.net.ssl.HostnameVerifier;@b@import javax.net.ssl.HttpsURLConnection;@b@import javax.net.ssl.SSLContext;@b@import javax.net.ssl.SSLSession;@b@import javax.net.ssl.TrustManager;@b@import javax.net.ssl.X509TrustManager;@b@@b@import com.alibaba.fastjson.JSONObject;@b@import com.alibaba.fastjson.serializer.SerializerFeature;@b@@b@public class HttpsUtils {@b@@b@	public static String METHOD_GET = "GET";@b@	public static String METHOD_POST = "POST";@b@@b@	public static int DEF_CONNECT_TIMEOUT = 2 * 1000;@b@	public static int DEF_READ_TIMEOUT = 8 * 1000;@b@	public static Charset DEF_CHARSET = Charset.forName("UTF-8");@b@@b@	public static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@b@		public java.security.cert.X509Certificate[] getAcceptedIssuers() {@b@			return new java.security.cert.X509Certificate[]{};@b@		}@b@		@Override@b@		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {@b@		}@b@		@Override@b@		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {@b@		}@b@	}};@b@	public static void trustAll() {@b@		try {@b@			SSLContext sc = SSLContext.getInstance("TLS");@b@			sc.init(null, trustAllCerts, new java.security.SecureRandom());@b@			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());@b@		} catch (Exception e) {@b@			e.printStackTrace();@b@		}@b@	}@b@	static {@b@		trustAll();@b@	}@b@@b@	public static String Get(String urlString) {@b@		return HttpsGo(urlString, METHOD_GET, null, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@	@b@	public static String Get(String urlString, Map<String, String> headers) {@b@		return HttpsGo(urlString, METHOD_GET, headers, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@	@b@	public static String Get(String urlString, Map<String, String> headers, Map<String, String> params) {@b@		if (params != null && params.isEmpty() == false) {@b@			StringBuffer url = new StringBuffer(urlString);@b@			try {@b@				boolean isFirst = true;@b@				if (urlString.contains("?")) {@b@					if (urlString.endsWith("&") == false && urlString.contains("&")) {@b@						isFirst = false;@b@					}@b@				} else {@b@					url.append('?');@b@				}@b@				String paramsEncoding = DEF_CHARSET.name();@b@				for (Map.Entry<String, String> entry : params.entrySet()) {@b@					if (isFirst) isFirst = false; else url.append('&');@b@					url.append(URLEncoder.encode(entry.getKey(), paramsEncoding));@b@					url.append('=');@b@					url.append(URLEncoder.encode(entry.getValue(), paramsEncoding));@b@				}@b@			} catch (Exception e) {@b@			}@b@			return Get(url.toString(), headers);@b@		} else {@b@			return Get(urlString, headers);@b@		}@b@	}@b@@b@	public static String Post(String urlString, String contentType, byte[] content) {@b@		Map<String, String> headers = new HashMap<String, String>(1);@b@		headers.put("Content-Type", contentType);@b@		return HttpsGo(urlString, METHOD_POST, headers, content, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@@b@	public static String FormPost(String urlString, String content) {@b@		Map<String, String> headers = new HashMap<String, String>(1);@b@		headers.put("Content-Type", String.format("application/x-www-form-urlencoded; charset=%s", DEF_CHARSET.name()));@b@		return HttpsGo(urlString, METHOD_POST, null, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@@b@	public static String XmlPost(String urlString, String content) {@b@		Map<String, String> headers = new HashMap<String, String>(1);@b@		headers.put("Content-Type", String.format("text/html; charset=%s", DEF_CHARSET.name()));@b@		return HttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@@b@	public static String JsonPost(String urlString, Object content) {@b@		return JsonPost(urlString, JSONObject.toJSONString(content, SerializerFeature.DisableCircularReferenceDetect));@b@	}@b@@b@	public static String JsonPost(String urlString, String content) {@b@		Map<String, String> headers = new HashMap<String, String>(1);@b@		headers.put("Content-Type", String.format("application/json; charset=%s", DEF_CHARSET.name()));@b@		return HttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@	}@b@@b@	public static String HttpsGo(String urlString, String method, Map<String, String> headers, byte[] content, int connectTimeout, int readTimeout) {@b@		HttpsURLConnection conn = null;@b@		try { @b@			conn = (HttpsURLConnection) new URL(urlString).openConnection();   @b@			@b@			SSLContext sc = SSLContext.getInstance("SSL");@b@			sc.init(null, trustAllCerts, new SecureRandom());@b@			conn.setHostnameVerifier(new HostnameVerifier() {@b@				@Override@b@				public boolean verify(String arg0, SSLSession arg1) {@b@					return true;@b@				}@b@			});@b@			conn.setSSLSocketFactory(sc.getSocketFactory());@b@			@b@			conn.setRequestMethod(method);  @b@			conn.setDoOutput(true);   @b@			conn.setDoInput(true);   @b@			conn.setUseCaches(false);@b@			conn.setConnectTimeout(connectTimeout);@b@			conn.setReadTimeout(readTimeout);@b@@b@			if (headers != null) {@b@				for (Map.Entry<String, String> entry : headers.entrySet()) {@b@					conn.addRequestProperty(entry.getKey(), entry.getValue());@b@				}@b@			}@b@			if (content != null) {@b@				if (headers == null || headers.containsKey("Content-Length") == false) {@b@					conn.addRequestProperty("Content-Length", Integer.toString(content.length));@b@				}@b@				OutputStream output = null;@b@				try {@b@					output = conn.getOutputStream();@b@					output.write(content);   @b@					output.flush();   @b@				} finally {@b@					if (output != null) try { output.close(); } catch (Exception e) { }@b@				}@b@			}@b@@b@			return readContent(conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream(), getCharset(conn));@b@		} catch (Exception e) {@b@			return null;@b@		} finally {   @b@			if (conn != null) conn.disconnect();   @b@		}  @b@	}@b@@b@	public static String encodeParams(Map<String, String> params, String paramsEncoding) throws Exception {@b@		boolean isFirst = true;@b@		StringBuilder encodedParams = new StringBuilder();@b@		for (Map.Entry<String, String> entry : params.entrySet()) {@b@			if (isFirst) isFirst = false; else encodedParams.append('&');@b@			encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));@b@			encodedParams.append('=');@b@			encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));@b@		}@b@		return encodedParams.toString();@b@	}@b@	@b@	public static String CHARSET_DEF = DEF_CHARSET.name();@b@	private static String CHARSET_STR = "charset=";@b@	private static int CHARSET_STR_LEN = CHARSET_STR.length();@b@	private static String getCharset(HttpURLConnection conn) {@b@		String contentType = conn.getHeaderField("Content-Type");@b@		int length = contentType != null ? contentType.length() : 0;@b@		if (length < CHARSET_STR_LEN) {@b@			return CHARSET_DEF;@b@		}@b@		int pos = contentType != null ? contentType.indexOf("charset=") : -1;@b@		if (pos < 0) {@b@			return CHARSET_DEF;@b@		}@b@		return contentType.substring(pos + CHARSET_STR_LEN);@b@	}@b@@b@	private static String readContent(InputStream input, String charset) throws Exception {@b@		try {@b@			int APPEND_LEN = 4 * 1024;@b@			int offset = 0;@b@			byte[] data = new byte[APPEND_LEN];@b@			while (true) {@b@				int len = input.read(data, offset, data.length - offset);@b@				if (len == -1) {@b@					break;@b@				}@b@				offset += len;@b@				if (offset >= data.length) {@b@					data = Arrays.copyOf(data, offset + APPEND_LEN);@b@				}@b@			}@b@			return charset != null ? new String(data, 0, offset, charset) : new String(data, 0, offset);@b@		} finally {@b@			if (input != null) try { input.close(); } catch (Exception e) { }@b@		}@b@	}@b@}
  • ◆ 相关内容