连接 org.apache.http.conn.HttpHostConnect 时出现超时错误

Posted

技术标签:

【中文标题】连接 org.apache.http.conn.HttpHostConnect 时出现超时错误【英文标题】:Timeout error while connecting org.apache.http.conn.HttpHostConnect 【发布时间】:2021-04-14 10:07:53 【问题描述】:

我正在尝试使用摘要授权进行 SOAP 活动。当我尝试连接到测试服务时,出现以下错误:

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

我为解决方案做了什么:

    更改了端口号 更改了网址 更改了启动项目的 PC...没有任何帮助:(

如果有任何帮助,我将不胜感激。代码:

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();
    

主要

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

【问题讨论】:

【参考方案1】:

结果证明解决方案非常简单。 我已经为我设置了正确的端口

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

我还禁用了防火墙。

【讨论】:

以上是关于连接 org.apache.http.conn.HttpHostConnect 时出现超时错误的主要内容,如果未能解决你的问题,请参考以下文章

MySQL 的内连接、左连接、右连接有啥区别?

SQL中的左连接与右连接,内连接有啥区别

sql左连接 右连接 内连接 外连接都是啥

oracle连接总结(内连接外连接自然连接,交叉连接,自连接)

SQL内连接与外连接的区别

SQL的连接(外连接内连接交叉连接和自连接)