0

I am currently working with Rest API calls to write an automation script in Java in which a Rest API connects into our internal xMatters application. Both my Java IDE (intellij) and Postman application are setup to deal with our company proxy. However when I run a simple API call (even to google.com) I get a successful connection from the Postman application but get a connection time out error from my code which can be seen in the following:

 com.mashape.unirest.http.exceptions.UnirestException: org.apache.http.conn.HttpHostConnectException: Connect to google.com:443 [google.com/74.125.193.113, google.com/74.125.193.138, google.com/74.125.193.100, google.com/74.125.193.101, google.com/74.125.193.139, google.com/74.125.193.102] failed: Connection timed out: connect
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
    at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:56)
    at Base.API_Unirest_Queries.getxMatrersBearerToken(API_Unirest_Queries.java:155)
    at IaaS_Reconciliation_Job_Health_Checks_Methods.IaaS_Reconciliation_Job_Health_Checks_Methods.xMattersNotify(IaaS_Reconciliation_Job_Health_Checks_Methods.java:453)
    at IaaS_Reconciliation_Job_Health_Checks_Methods.IaaS_Reconciliation_Job_Health_Checks_Methods.check_IaaS_Reconciliation_Job_Status(IaaS_Reconciliation_Job_Health_Checks_Methods.java:36)
    at IaaS_Reconciliation_Job_Health_Check.IaaS_Reconciliation_Job_Health_Check_Tests.CheckIaaSReconciliationJob(IaaS_Reconciliation_Job_Health_Check_Tests.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:73)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to google.com:443 [google.com/74.125.193.113, google.com/74.125.193.138, google.com/74.125.193.100, google.com/74.125.193.101, google.com/74.125.193.139, google.com/74.125.193.102] failed: Connection timed out: connect
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:158)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:138)
    ... 28 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:337)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
    ... 39 moreom.mashape.unirest.http.exceptions.UnirestException: org.apache.http.conn.HttpHostConnectException: Connect to google.com:443 [google.com/74.125.193.113, google.com/74.125.193.138, google.com/74.125.193.100, google.com/74.125.193.101, google.com/74.125.193.139, google.com/74.125.193.102] failed: Connection timed out: connect
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
    at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:56)
    at Base.API_Unirest_Queries.getxMatrersBearerToken(API_Unirest_Queries.java:155)
    at IaaS_Reconciliation_Job_Health_Checks_Methods.IaaS_Reconciliation_Job_Health_Checks_Methods.xMattersNotify(IaaS_Reconciliation_Job_Health_Checks_Methods.java:453)
    at IaaS_Reconciliation_Job_Health_Checks_Methods.IaaS_Reconciliation_Job_Health_Checks_Methods.check_IaaS_Reconciliation_Job_Status(IaaS_Reconciliation_Job_Health_Checks_Methods.java:36)
    at IaaS_Reconciliation_Job_Health_Check.IaaS_Reconciliation_Job_Health_Check_Tests.CheckIaaSReconciliationJob(IaaS_Reconciliation_Job_Health_Check_Tests.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:73)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to google.com:443 [google.com/74.125.193.113, google.com/74.125.193.138, google.com/74.125.193.100, google.com/74.125.193.101, google.com/74.125.193.139, google.com/74.125.193.102] failed: Connection timed out: connect
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:158)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:138)
    ... 28 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:337)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
    ... 39 more

The code is as follows and was obtained through the postman call -> code feature and is completed using Unirest.

    public HttpResponse<String> getxMatrersBearerToken(String username, String password) {
    setSSLCert();
    HttpResponse<String> response2 = null;

    try {
        response2 = Unirest.get("https://google.com")
                .asString();

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return response2;

}

The setSSL Cert method is as follows:

private void setSSLCert(){
    try {
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        Unirest.setHttpClient(httpclient);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        e.printStackTrace();
    }
}

Obviously the error message shows that the code is failing due to a connection time out cause by a socket exception. My first question is how would I go about fixing this issue? A follow up question now is: What would be the reasoning behind Postman being able to run a simple call to google and get a success result but my code failing? Any help appreciated.

Thanks in advance.

MarkMck
  • 1
  • 1
  • 1

1 Answers1

0

I have given this answer few years back

You can try following code

    package com.khan.vaquar;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;

    public class SSLTestClient extends DefaultHttpClient {
        public SSLTestClient() throws Exception{
            super();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
                    }
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, sslSocketFactory));
        }
    }



    package com.khan.vaquar;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.util.EntityUtils;



    public class HttpClientUtil {
        @SuppressWarnings("resource")
        public static String doPost(String url,String jsonstr,String charset){
            HttpClient httpClient = null;
            HttpPost httpPost = null;
            String result = null;
            try{
                httpClient = new SSLClient();
                httpPost = new HttpPost(url);
                httpPost.addHeader("Content-Type", "application/json");
                StringEntity se = new StringEntity(jsonstr);
                se.setContentType("text/json");
                se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
                httpPost.setEntity(se);
                HttpResponse response = httpClient.execute(httpPost);
                if(response != null){
                    HttpEntity resEntity = response.getEntity();
                    if(resEntity != null){
                        result = EntityUtils.toString(resEntity,charset);
                    }
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
            return result;
        }
    }



    package com.khan.vaquar;

    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.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.ssl.SSLContextBuilder;
     
    public class HttpTestSSLUtil {
        public CloseableHttpClient createSSLClientDefault(){
            try {
                 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                     public boolean isTrusted(X509Certificate[] chain,
                                     String authType) throws CertificateException {
                         return true;
                     }
                 }).build();
                 SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
                 return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
             } catch (Exception e) {
                 e.printStackTrace();
             } 
            return  HttpClients.createDefault();
        }
    }

Test SSL:

    package com.khan.vaquar;

        public static void main(String[] args) {
            String url = "https://www.google.com/";
            String jsonStr = "{}";
            String httpTestRtn = HttpTestSSLUtil.doPost(url, jsonStr, "utf-8");
            System.out.println(httpTestRtn);
        }
vaquar khan
  • 10,864
  • 5
  • 72
  • 96