赞
踩
最近在做一个接口请求的时候,遇到javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure这个异常,怎么也处理不了,最后发现是jar包的问题,在通过https访问的时候安全机制策略有问题,这个是jdk导致的,jdk里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,替换以后bug就处理了。
目录 %JAVA_HOME%\jre\lib\security里的local_policy.jar,US_export_policy.jar
JDK7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
在请求发送之前添加 System.setProperty("https.protocols", "TLSv1.2"); 有时候不生效
/**
* post请求(用于key-value格式的参数)
*
* @param url
* @param params
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String doPostt(String url, Map params) {
try {
javax.net.ssl.SSLContext ctx = SSLContexts.custom()
.useProtocol("TLSv1.2").build();
// 定义HttpClient
HttpClient client = HttpClientBuilder.create().setSslcontext(ctx)
.build();
BufferedReader in = null;
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
// 设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
// System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if (code == 200) { // 请求成功
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
} else { //
System.out.println("状态码:" + code);
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。