无法使用Apache HTTP POST到https

时间:2016-12-21 19:34:12

标签: java apache https

我花了好几个小时才弄明白为什么。我甚至使用bls.gov网站上使用的部分代码示例。我不应该有任何问题,因为它是一个公共API ...请帮助!

public static void main(String[] args) throws ClientProtocolException, IOException {

     HttpHost proxy = new HttpHost("myproxy.com", 3128, "http");

    CloseableHttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build(); // Use
                                                                            // this
                                                                            // instead

    HttpPost request = new HttpPost("https://api.bls.gov/publicAPI/v1/timeseries/data/");
    StringEntity params = new StringEntity("{\"seriesid\":[\"LAUCN040010000000005\", \"LAUCN040010000000006\"]}");

    request.setEntity(params);

    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");

    CloseableHttpResponse response = httpClient.execute(request);
    System.out.println("HERE");
    System.out.println(response.getStatusLine());
    response.close();

继续收到此错误:

  Exception in thread "main" 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
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)

2 个答案:

答案 0 :(得分:0)

Java对证书链非常挑剔。服务器是否也提供中间证书?

https://en.m.wikipedia.org/wiki/Intermediate_certificate_authority

不是你。证书的顺序未正确传递:https://www.ssllabs.com/ssltest/analyze.html?d=api.bls.gov

答案 1 :(得分:0)

您必须在Java Trust存储区中拥有https://api.bls.gov的证书。

当连接到该URL时,您可以从任何浏览器导入证书。

您必须将证书添加到Trust store中,该证书将用于您的程序。 您可以使用keytool或OpenSSL来完成。

有许多不同的方法可以定义将使用哪个Trust存储:

  1. 可以在JRE级别将证书添加到Java默认信任库。 信任库是JRE lib / security文件夹中的cacerts。 - 不推荐

  2. 可以在启动时将证书添加到JVM级别上提供的Trust存储中 -Djavax.net.ssl.trustStore参数 - 不推荐(信任商店密码必须以-Djavax.net.ssl.trustStorePassword中的开放文字形式提供)

  3. 从所需的Trust商店文件(以及HostnameVerifier)创建SSLSocketFactory,然后将它们用于您的https连接。

  4. 互联网上到处都有很多例子。试着谷歌吧。