Java代码忽略https证书:解决No subject alternative names present问题 HttpURLConnection https请求
Java代码忽略https证书:解决No subject alternative names present问题
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * Java代码忽略https证书:解决No subject alternative names present问题 */ public class HttpsUtils { private static final Logger logger = LoggerFactory.getLogger(HttpsUtils.class); public static String get(String hosturl,String params,String contentType) throws IOException, KeyManagementException, NoSuchAlgorithmException { HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier()); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); URL url = new URL(hosturl+"?"+params); logger.info("参数:"+hosturl+"?"+params); // 打开restful链接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");// POST GET PUT DELETE conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // 设置访问提交模式,表单提交 // conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // conn.setRequestProperty("Content-Type",contentType); conn.setConnectTimeout(130000);// 连接超时 单位毫秒 conn.setReadTimeout(130000);// 读取超时 单位毫秒 // 读取请求返回值 byte bytes[] = new byte[1024]; InputStream inStream = conn.getInputStream(); inStream.read(bytes, 0, inStream.available()); logger.info("返回结果:" + new String(bytes, "utf-8")); return new String(bytes, "utf-8"); } /** * * @param hosturl * @param params * @param contentType text/plain;charset=utf-8 application/json;charset=utf-8 * @return * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ public static String post(String hosturl,String params,String contentType) { StringBuffer result = new StringBuffer(); OutputStream os = null; InputStream is = null; BufferedReader br = null; HttpURLConnection conn = null; try { HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier()); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // URL url = new URL(hosturl+"?"+params); // logger.info("参数:"+hosturl+"?"+params); URL url = new URL(hosturl); logger.info("参数url:" + hosturl +",params:"+ params); // 打开restful链接 conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");// POST GET PUT DELETE conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // 设置访问提交模式,表单提交 // conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // conn.setRequestProperty("Content-Type",contentType); conn.setConnectTimeout(130000);// 连接超时 单位毫秒 conn.setReadTimeout(130000);// 读取超时 单位毫秒 //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个 //设置是否可读取 conn.setDoOutput(true); conn.setDoInput(true); //拼装参数 if (null != params && !params.equals("")) { //设置参数 os = conn.getOutputStream(); //拼装参数 os.write(params.getBytes("UTF-8")); logger.info("发送请求参数成功,params:"+params); } // 读取请求返回值,收不到返回?? // byte bytes[] = new byte[1024]; // InputStream inStream = conn.getInputStream(); // inStream.read(bytes, 0, inStream.available()); // logger.info("返回结果:" + new String(bytes, "utf-8")); // return new String(bytes, "utf-8"); //读取响应 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); if (null != is) { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String temp = null; while (null != (temp = br.readLine())) { result.append(temp); result.append("\r\n"); } }else{ logger.error("连接获取返回inputStream null"); } } logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString()); }catch (Exception e) { logger.error("post exception:",e); }finally { //关闭连接 if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //关闭连接 conn.disconnect(); } return result.toString(); } /** * * @param hosturl * @param params * @param contentType * @return * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ public static String postJson(String hosturl,String params,String contentType) { StringBuffer result = new StringBuffer(); OutputStream os = null; InputStream is = null; BufferedReader br = null; HttpURLConnection conn = null; try { HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier()); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); URL url = new URL(hosturl); logger.info("参数url:" + hosturl + ",params=" + params); // 打开restful链接 conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");// POST GET PUT DELETE // 设置访问提交模式,表单提交 // conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // conn.setRequestProperty("Content-Type",contentType); //设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.setConnectTimeout(130000);// 连接超时 单位毫秒 conn.setReadTimeout(130000);// 读取超时 单位毫秒 //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个 //设置是否可读取 conn.setDoOutput(true); conn.setDoInput(true); //拼装参数 if (null != params && !params.equals("")) { //设置参数 os = conn.getOutputStream(); //拼装参数 os.write(params.getBytes("UTF-8")); logger.info("发送请求参数成功,params:"+params); } //读取响应 // 读取请求返回值,收不到返回?? // if (conn.getResponseCode() == 200) { // 读取请求返回值 // byte bytes[] = new byte[1024]; // InputStream inStream = conn.getInputStream(); // inStream.read(bytes, 0, inStream.available()); // logger.info("返回结果:" + new String(bytes, "utf-8")); // return new String(bytes, "utf-8"); // } // return null; //读取响应 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); if (null != is) { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String temp = null; while (null != (temp = br.readLine())) { result.append(temp); result.append("\r\n"); } }else{ logger.error("连接获取返回inputStream null"); } } logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString()); }catch (Exception e) { logger.error("postJson exception:",e); }finally { //关闭连接 if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //关闭连接 conn.disconnect(); } return result.toString(); } static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } } }; public class NullHostNameVerifier implements HostnameVerifier { /* * (non-Javadoc) * * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, * javax.net.ssl.SSLSession) */ @Override public boolean verify(String arg0, SSLSession arg1) { // TODO Auto-generated method stub return true; } } }