简体   繁体   中英

Timeout error while connecting org.apache.http.conn.HttpHostConnect

I am trying to make a SOAP activity with digest authorization. When i am trying to connect to the test service, I get the below error:

Exception in thread "main" org.apache.http.conn.HttpHostConnectException: Connect to httpbin.org:135 [httpbin.org/34.231.30.52, httpbin.org/54.166.163.67, httpbin.org/54.91.118.50, httpbin.org/34.199.75.4] 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:359)
  at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
  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:111)
  at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
  at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
  at SOAPClientApache.run(SOAPClientApache.java:94)
  at Main.main(Main.java:4)
Caused by: java.net.ConnectException: Connection timed out: connect
  at java.base/java.net.PlainSocketImpl.connect0(Native Method)
  at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:101)
  at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
  at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
  at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
  at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.base/java.net.Socket.connect(Socket.java:609)
  at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:339)
  at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
    ... 10 more

What I did for the solution:

  1. Changed the port number
  2. Changed the URL
  3. Changed the PC on which the project was launched...Nothing helped me:(

I would be grateful for any help. Code:

SOAPClientApache

import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.*;
import org.apache.http.ssl.SSLContextBuilder;
import org.testng.Assert;

import javax.net.ssl.*;

public class SOAPClientApache {


private static final String URL = "http://httpbin.org/digest-auth/auth/user/passwd";
//private static final String URL = "https://www.google.com/";

private static final String PASSWORD = "";

private static final String USER = "";

public void run() throws Exception {

    HttpGet httpget = new HttpGet(URL);

    HttpHost target
            = new HttpHost(httpget.getURI().getHost(), 135, "https");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(USER, PASSWORD);
    credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            credentials);

    CookieStore cookieStore = new BasicCookieStore();

    //Start fix SSL (убиваем проверку сертификатов)
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });
    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    //End fix SSL

    //SSL solution (ДО обхода проверки SSL)
    /*CloseableHttpClient httpclient
            = HttpClients.custom().setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credsProvider).build();*/


    CloseableHttpClient httpclient
            = HttpClients.custom().setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSF).build();

    try {

        DigestScheme digestAuth = new DigestScheme();

        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());

        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, digestAuth);

        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        CloseableHttpResponse response;

        response = httpclient.execute(target, httpget, localContext);
        Map<String, String> wwwAuth = Arrays
                .stream(response.getHeaders("WWW-Authenticate")[0]
                        .getElements())
                .collect(Collectors.toMap(HeaderElement::getName,
                        HeaderElement::getValue));

        // the first call ALWAYS fails with a 401
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);

        digestAuth.overrideParamter("opaque", wwwAuth.get("opaque"));
        digestAuth.overrideParamter("nonce", wwwAuth.get("nonce"));
        digestAuth.overrideParamter("realm", wwwAuth.get("Digest realm"));
        Header authenticate = digestAuth.authenticate(credentials, httpget,
                localContext);
        httpget.addHeader(authenticate);

        response = httpclient.execute(target, httpget, localContext);

        // the 2nd call is the real deal
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);

        System.out.println(IOUtils
                .toString(response.getEntity().getContent(), "utf-8"));


    } finally {
        httpclient.close();
    }
}

}

Main

public class Main {
    public static void main(String[] args) throws Exception {
        SOAPClientApache soapClientApache = new SOAPClientApache();
        soapClientApache.run();
    }
}

The solution turned out to be quite simple. I have set the correct port for me

HttpHost target = new HttpHost(httpget.getURI().getHost(), 443, "https");

I also disabled my firewall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM