赞
踩
在日常开发或者测试中,通常会遇到需要用httpclient客户端调用对方http是服务器的场景,由于没有证书,所以直接是无法调用的。采用下面的方法可以绕过证书验证:
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } }}; // 创建一个SSL上下文,设置信任管理器 try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); }
完整代码:
public static String sendHttpPostRequest(String url, JSONObject param) throws Exception { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } }}; // 创建一个SSL上下文,设置信任管理器 try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } URL apiUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); // 设置请求方法为 POST connection.setRequestMethod("POST"); connection.setDoOutput(true); // 添加请求头 connection.setRequestProperty("Content-Type", "application/json"); //connection.setRequestProperty("", accessToken); // 发送 POST 请求必须设置如下两行 OutputStream outputStream = connection.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); outputStreamWriter.write(param.toJSONString()); outputStreamWriter.flush(); outputStreamWriter.close(); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); // 创建一个 BufferedReader 来读取服务器的响应 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer response = new StringBuffer(); String inputLine; while ((inputLine = bufferedReader.readLine()) != null) { response.append(inputLine); } bufferedReader.close(); System.out.println("Response: " + response.toString()); return null; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。