调用服务工具类-HttpsUtil

时间:2025-03-12 08:18:05
import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .X509Certificate; import ; import ; import ; import ; import ; import ; import ; import ; import .X509TrustManager; import .; public class HttpsUtil { /** * post请求方法 */ private static final String METHOD_POST = "POST"; /** * utf-8编码格式 */ private static final String DEFAULT_CHARSET = "utf-8"; /** * doPost * * @param url * 请求地址 * @param params * 请求参数 * @param charset * 编码 * @param ctype * 类型 * @param connectTimeout * 连接超时时间 * @param readTimeout * 读取超时时间 * @return 结果 * @throws Exception * 异常 */ public static String doPost(String url, String params, String charset, String ctype, int connectTimeout, int readTimeout) throws Exception { charset = (charset == null || "".equals(charset)) ? DEFAULT_CHARSET : charset; byte[] content = {}; if (params != null) { content = (charset); } return doPost(url, ctype, content, connectTimeout, readTimeout); } /** * doPost * * @param url * 请求地址 * @param ctype * 类型 * @param content * 内容 * @param connectTimeout * 连接超时时间 * @param readTimeout * 读取超时时间 * @return 结果 * @throws Exception * 异常 */ public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null; String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); (new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); (new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); (connectTimeout); (readTimeout); } catch (Exception e) { // ("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = (); (content); rsp = getResponseAsString(conn); } catch (IOException e) { // ("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { (); } if (conn != null) { (); } } return rsp; } private static class DefaultTrustManager 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; } } /** * 获取连接 * * @param url * 请求地址 * @param method * 请求方法 * @param ctype * 类型 * @return HttpsURLConnection * @throws IOException * 异常 */ private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException { HttpsURLConnection conn = (HttpsURLConnection)(); (method); (true); (true); ("Accept", "text/xml,text/javascript,text/html"); ("User-Agent", "stargate"); ("Content-Type", ctype); return conn; } /** * getResponseAsString * * @param conn * conn连接 * @return String * @throws IOException * IOException */ protected static String getResponseAsString(HttpURLConnection conn) throws IOException { String charset = getResponseCharset(()); InputStream es = (); if (es == null) { return getStreamAsString((), charset); } else { String msg = getStreamAsString(es, charset); if (StringUtils.isEmpty(msg)) { throw new IOException(() + ":" + ()); } else { throw new IOException(msg); } } } /** * getStreamAsString * * @param stream * stream * @param charset * charset * @return String * @throws IOException * IOException */ private static String getStreamAsString(InputStream stream, String charset) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset)); StringWriter writer = new StringWriter(); char[] chars = new char[256]; int count = 0; while ((count = (chars)) > 0) { (chars, 0, count); } return (); } finally { if (stream != null) { (); } } } /** * getResponseCharset * * @param ctype * ctype * @return String */ private static String getResponseCharset(String ctype) { String charset = DEFAULT_CHARSET; if (!StringUtils.isEmpty(ctype)) { String[] params = (";"); for (String param : params) { param = (); if (("charset")) { String[] pair = ("=", 2); if (pair.length == 2) { if (!StringUtils.isEmpty(pair[1])) { charset = pair[1].trim(); } } break; } } } return charset; } private static class TrustAnyHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } } /** * doGet * * @param url * 请求地址 * @param keyValueParams * 参数 * @param cypt * cypt * @return String * @throws Exception * Exception */ public static String doGet(String url, Map<String, String> keyValueParams, String cypt) throws Exception { String result = ""; BufferedReader in = null; try { String urlStr = url + "?" + getParamStr(keyValueParams); // ("GET请求的URL为:"+urlStr); SSLContext sc = SSLContext.getInstance("SSL"); (null, new TrustManager[] {new DefaultTrustManager()}, new ()); URL realUrl = new URL(urlStr); // 打开和URL之间的连接 HttpsURLConnection connection = (HttpsURLConnection)(); // 设置https相关属性 (()); (new TrustAnyHostnameVerifier()); (true); // 设置通用的请求属性 ("accept", "*/*"); ("Content-type", cypt); ("connection", "Keep-Alive"); ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 (); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader((), "UTF-8")); String line; while ((line = ()) != null) { result += line; } // ("获取的结果为:"+result); } catch (Exception e) { // ("发送GET请求出现异常!" + e); // (); throw e; } // 使用finally块来关闭输入流 finally { try { if (in != null) { (); } } catch (Exception e2) { // (); throw e2; } } return result; } /** * 转化字符串参数 * * @param params * 参数 * @return String */ public static String getParamStr(Map<String, String> params) { String paramStr = StringUtils.EMPTY; if (null == params || 0 == ()) { return paramStr; } // 获取参数列表组成参数字符串 for (String key : ()) { paramStr += key + "=" + (key) + "&"; } // 去除最后一个"&" return (0, () - 1); } /** * 解析出url参数中的键值对 如 "?Action=del&id=123",解析出Action:del,id:123存入map中 * * @param url * url地址 * @return url请求参数部分 * @author lzf */ public static Map<String, String> getUrlParam(String url) { // 初始化返回 Map<String, String> params = new HashMap<String, String>(); if (StringUtils.isBlank(url)) { return params; } // String strUrlParam = truncateUrl(url); if (StringUtils.isBlank(strUrlParam)) { return params; } String[] arrSplit = ("[&]"); for (String strSplit : arrSplit) { String[] arrSplitEqual = ("[=]"); // 解析出键值 if (arrSplitEqual.length > 1) { // 正确解析 (arrSplitEqual[0], arrSplitEqual[1]); } else { if (!"".equals(arrSplitEqual[0])) { // 只有参数没有值,也加入 (arrSplitEqual[0], ""); } } } return params; } /** * 去掉url中的路径,留下请求参数部分 * * @param url * url地址 * @return url * @author lzf */ private static String truncateUrl(String url) { String strAllParam = null; String[] arrSplit = null; url = (); arrSplit = ("[?]"); if (() > 1) { if (arrSplit.length > 1) { for (int i = 1; i < arrSplit.length; i++ ) { strAllParam = arrSplit[i]; } } } return strAllParam; } }