AWS API Gateway - Тайм-аут соединения при доступе к API с помощью Spring RestTemplate в Java, где он нормально работает с помощью Postman - PullRequest
0 голосов
/ 28 марта 2019

Я создал API на AWS API Gateway. Когда я получаю доступ к этому с помощью почтальона, он работает нормально, но когда я пытаюсь получить доступ к этому в Java с помощью Spring RestTemplate, это дает мне ошибку времени ожидания соединения. Я попробовал с ниже различными подходами клиента остальных. Но не повезло. Не уверен, какую ошибку я делаю в коде ниже.

Обратите внимание, что я изменил URI и IP-адреса в приведенном ниже коде / исключении, поскольку не хочу раскрывать фактические URl и IP-адреса.

Approach-1

final String uri = "https://xyz.execute-api.us-east-2.amazonaws.com/dev/dynamodb/users/55";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

System.out.println(result);

Approach-2

CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

final String uri = "https://xyz.execute-api.us-east-2.amazonaws.com/dev/dynamodb/users/55";

String result = restTemplate.getForObject(uri, String.class); 

System.out.println(result);  

Получение ниже исключения, когда я вызываю API, используя вышеуказанный код Java / Spring.

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://xyz.execute-api.us-east-1.amazonaws.com/dev/dynamodb/users/55": Connect to xyz.execute-api.us-east-1.amazonaws.com:443 [xyz.execute-api.us-east-1.amazonaws.com/11.11.232.11, xyz.execute-api.us-east-1.amazonaws.com/52.200.98.93, xyz.execute-api.us-east-1.amazonaws.com/11.81.200.210] failed: Connection timed out: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to xyz.execute-api.us-east-1.amazonaws.com:443 [xyz.execute-api.us-east-1.amazonaws.com/11.11.232.11, xyz.execute-api.us-east-1.amazonaws.com/52.200.98.93, xyz.execute-api.us-east-1.amazonaws.com/11.81.200.210] failed: Connection timed out: connect
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:669)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:310)
    at com.adp.taxcredits.connector.icims.services.CachingServiceImpl.main(CachingServiceImpl.java:46)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to xyz.execute-api.us-east-1.amazonaws.com:443 [xyz.execute-api.us-east-1.amazonaws.com/11.11.232.11, xyz.execute-api.us-east-1.amazonaws.com/52.200.98.93, xyz.execute-api.us-east-1.amazonaws.com/11.81.200.210] failed: Connection timed out: connect
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:394)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:734)
    ... 3 more
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:339)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
    ... 16 more

1 Ответ

0 голосов
/ 29 марта 2019

Наконец-то у меня получилось работать с приведенным ниже кодом.

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestTemplateUtil {

    public static RestTemplate restTemplate; 

    public static  RestTemplate getRestTemplate()
            throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        if(restTemplate != null) {
            return restTemplate;
        }

        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        HttpClientBuilder builder = HttpClients.custom();
        builder.setSSLSocketFactory(csf);
        builder.setProxy(new HttpHost("youproxy.com", 8080, "http"));
        CloseableHttpClient httpClient = builder.build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

}
...