无法通过代理调用API

时间:2018-09-20 07:34:37

标签: java api http tomcat

我在本地Tomcat服务器上部署了一个Java应用程序。该应用程序需要调用一些API才能正常工作,但是不幸的是,使用不同的方法会遇到不同的异常,而且我不知道如何解决此问题。当我在本地运行此代码段时,它工作正常。但是在部署之后,它不再起作用。 我尝试的第一件事是:

        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost(apiAdress, 443, "HTTPS");
        HttpHost proxy = new HttpHost(proxyAdress, 80, "HTTP");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet(getPath);
        request.setConfig(config);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            LOG.debug("----------------------------------------");
            LOG.debug(response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();
            if(responseEntity!=null) {
                String responseString = EntityUtils.toString(responseEntity);
                return JsonUtils.getObjectFromJson(responseString, NachrichtenResponse.class);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(),e);
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        LOG.error(ex.getMessage(),ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;

这导致以下异常:

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:146)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 106 common frames omitted

当我将代理方案更改为HTTPS时

HttpHost proxy = new HttpHost("94.100.132.14", 80, "HTTPS");

这导致以下异常:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

,并且没有配置代理,我得到了异常连接被拒绝。我真的不知道问题出在哪里,我在解决这个问题上遇到了麻烦。有没有人遇到过类似的问题并且对此有解决方案?

1 个答案:

答案 0 :(得分:-1)

您是否不必将证书添加到信任库中?