我在服务器使用HttpClient,请求钉钉API(oapi.dingtalk.com/gettoken)。
在本地跑没有问题,在钉钉里作为微应用跑,就会出错。
错误信息:
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
JAVA代码:
String accessToken = "";
String code = request.getParameter("code");
logger.info("code=" + code);
HttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 建立连接
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("corpid", "XXXXXX"));
parameters.add(new BasicNameValuePair("corpsecret", "XXXXXX"));
String query = URLEncodedUtils.format(parameters, "UTF-8");
HttpGet getRequest = new HttpGet("https://oapi.dingtalk.com/gettoken?" + query);
// POST请求请在HTTP Header中设置 Content-Type:application/json,否则接口调用失败
getRequest.addHeader("Content-type", "application/json");
logger.info("url=" + getRequest.getURI().toString());
response = httpClient.execute(getRequest);// 走到这句的时候,报错了。
在论坛里搜了搜,没有找到类似的问题,
请教是什么原因,以及如何解决?
初次提问题,不知问题描述明白了没,还望指正。
-------------------------
-------------------------
-------------------------
-------------------------
-------------------------
HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
});
HttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 建立连接
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("corpid", "XXXXXX"));
parameters.add(new BasicNameValuePair("corpsecret", "XXXXXX"));
String query = URLEncodedUtils.format(parameters, "UTF-8");
HttpGet getRequest = new HttpGet("Https://oapi.dingtalk.com/gettoken?" + query);
// POST请求请在HTTP Header中设置 Content-Type:application/json,否则接口调用失败
getRequest.addHeader("Content-type", "application/json");
logger.info("url=" + getRequest.getURI().toString());
response = httpClient.execute(getRequest);// 跑到这里报错了。
-------------------------
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) {
}
} };
// "TLSv1.2"不正确的话,会出现"Received fatal alert: handshake_failure"异常
// Ref:logback.qos.ch/manual/usingSSL_ja.html
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sc);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。