java httpget 报错sun.security.validator.ValidatorException: PKIX path building failed
/**
* 信任SSL证书
* @return
*/
public static CloseableHttpClient buildDefaultHttpClientTrustSSL()
{
SSLContext sslContext = null;
try {
sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
} catch (Exception e) {
e.printStackTrace();
}
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setContentCompressionEnabled(true)
.build();
return HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
}
//测试
public static void main(String[] args) throws IOException {
String pdfUrl = "https://www.nia.gov.cn/newspaper/2023/June/ChinaImmigrationNewspaperJune/files/mobile/1.jpg";
try {
CloseableHttpClient httpClient = buildDefaultHttpClientTrustSSL();//信任证书
HttpGet httpGet = new HttpGet(pdfUrl);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.58");
httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpGet.addHeader("Accept-Encoding", "gzip, deflate");
httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
CloseableHttpResponse resp = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(resp.getEntity(), "utf-8");
System.out.print(responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}