java调用百度api接口报错javax.net.ssl.SSLHandshakeException PKIX path building failed unable to find valid certification path to requested target
报错信息
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
解决方法
如果是百度的sdk,则原源码中有AipHttpClient这个类,打开post方法
public static AipResponse post(AipRequest request) {
String url;
String charset = request.getContentEncoding();
String content = request.getBodyStr();
HashMap<String, String> header = request.getHeaders();
AipResponse response = new AipResponse();
DataOutputStream out = null;
InputStream is = null;
try {
if (request.getParams().isEmpty()) {
url = request.getUri().toString();
}
else {
url = String.format("%s?%s", request.getUri().toString(), request.getParamStr());
}
URL console = new URL(url);
Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);
// set timeout
if (request.getConfig() != null) {
conn.setConnectTimeout(request.getConfig().getConnectionTimeoutMillis());
conn.setReadTimeout(request.getConfig().getSocketTimeoutMillis());
}
conn.setDoOutput(true);
// 添加header
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
out.flush();
int statusCode = conn.getResponseCode();
response.setHeader(conn.getHeaderFields());
response.setStatus(statusCode);
response.setCharset(charset);
if (statusCode != 200) {
return response;
}
is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
response.setBody(outStream.toByteArray());
}
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
修改为:
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidu.aip.http;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import com.baidu.aip.util.SSL;
public class AipHttpClient {
/**
* post方式请求服务器(https协议)
*
* @param request 请求内容
* @return AipResponse
*/
public static AipResponse post(AipRequest request) {
String url;
String charset = request.getContentEncoding();
String content = request.getBodyStr();
HashMap<String, String> header = request.getHeaders();
AipResponse response = new AipResponse();
DataOutputStream out = null;
InputStream is = null;
try {
if (request.getParams().isEmpty()) {
url = request.getUri().toString();
}
else {
url = String.format("%s?%s", request.getUri().toString(), request.getParamStr());
}
URL console= new URL(null, url, new sun.net.www.protocol.https.Handler());
Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);
SSL addSSL = new SSL();
addSSL.trustAllHosts((HttpsURLConnection)conn);
((HttpsURLConnection) conn).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
// set timeout
if (request.getConfig() != null) {
conn.setConnectTimeout(request.getConfig().getConnectionTimeoutMillis());
conn.setReadTimeout(request.getConfig().getSocketTimeoutMillis());
}
conn.setDoOutput(true);
// 添加header
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
out.flush();
int statusCode = conn.getResponseCode();
response.setHeader(conn.getHeaderFields());
response.setStatus(statusCode);
response.setCharset(charset);
if (statusCode != 200) {
return response;
}
is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
response.setBody(outStream.toByteArray());
}
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
}
修改的内容为:
将
URL console = new URL(url);
Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);
替换为:
URL console= new URL(null, url, new sun.net.www.protocol.https.Handler());
Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);
SSL addSSL = new SSL();
addSSL.trustAllHosts((HttpsURLConnection)conn);
((HttpsURLConnection) conn).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
要用到的一个类SSL如下:
package com.baidu.aip.util;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSL {
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
}};
/**
* 设置不验证主机
*/
public static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* 信任所有
*
* @param connection
* @return
*/
public static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
e.printStackTrace();
}
return oldFactory;
}
}
猜你喜欢
official
614
git报错PushfailedUnabletoaccess'https://github.com/xx.git/':Failedtoconnecttogithub.comport443
blog
前端使用layui分页
前端(h5)
1779
; varform=layui.form; functionsel(message,page,limit){ $.ajax({ url:'${path}/interview/select',
blog
linux ssh远程复制文件
linux
1146
假如服务器A,B都有ssh服务,现在在A服务器中。一、从A复制到B(推过去)scp-rp/path/filenameusername@remoteIP:/path二、从B复制到A(拉过来)scp-rpusername@remoteIP:/path/filename/path
spring/springmvc
4345
我在之前进行接口开发的时候经常会有大量的参数验证,而我一般的操作方法就是在controller中进行参数的校验,这样并没有什么错,但是代码略显臃肿,而使用springboot的@vaild注解可以减
nginx
1329
@localhostnginx]#./sbin/nginx 默认80端口,记得开放端口。五、nginx常用命令./sbin/nginx启动nginx./sbin/nginx-sstop停止nginx,可
框架
2546
参数校验失败统一返回给前端异常信息参数校验如何使用参考:http://www.jiajiajia.club/blog/artical/yjw520/248校验需要的pom依赖
工具
2905
/dependency2.java代码调用SoapClientclient=SoapClient.create("http://cwzf.zzcsjr.edu.cn/xysf/OrderView.asmx")//设
blog
linux系统maven环境变量配置
linux系统
1624
-Xmx1024m"exportPATH=$M2_HOME/bin:$PATH使生效:source/etc/profile配置maven仓库:setting.xml配置文件中在各自的标签中添加:mirrorida
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。