GVKun编程网logo

Apache HTTPClient SSLPeerUnverifiedException

24

对于想了解ApacheHTTPClientSSLPeerUnverifiedException的读者,本文将提供新的信息,并且为您提供关于androidhttpclients报java.lang.Ve

对于想了解Apache HTTPClient SSLPeerUnverifiedException的读者,本文将提供新的信息,并且为您提供关于android httpclients 报 java.lang.VerifyError: org/apache/http/conn/ssl/DefaultHostnameVerifier、Apache Curator与Zookeeper版本兼容性异常:org.apache.zookeeper.KeeperException$UnimplementedException: KeeperE、Apache DefaultHttpClient调用的结果为“ java.lang.RuntimeException:Stub!”、Apache HttpClient临时错误:NoHttpResponseException的有价值信息。

本文目录一览:

Apache HTTPClient SSLPeerUnverifiedException

Apache HTTPClient SSLPeerUnverifiedException

使用Apache HttpClient 4.2.1。使用从基于表单的登录示例复制的代码

http://hc.apache.org/httpcomponents-client-
ga/examples.html

访问受SSL保护的登录表单时出现异常:

Getting library items from https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=blankjavax.net.ssl.SSLPeerUnverifiedException: peer not authenticatedClosing http connectionat sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:572)at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)

据我所知,该证书很好(请参阅堆栈跟踪之前的URL),并且不会过期-浏览器不会抱怨。

我尝试将证书导入到我的密钥库中

如何使用Apache
HttpClient处理无效的SSL证书?

没有变化。我相信您可以创建一个自定义SSLContext来强制Java忽略该错误,但是我宁愿解决根本原因,因为我不想打开任何安全漏洞。

有任何想法吗?

答案1

小编典典

编辑 我知道这个答案很久以前就被接受了,并且也被投票了3次,但这是(至少部分是)错误的,所以这里有更多关于此异常的信息。不便之处敬请原谅。

javax.net.ssl.SSLPeerUnverifiedException:对等方未通过身份验证

当远程服务器根本不发送证书时, 通常会 抛出此异常。但是,由于在此版本sun.security.ssl.SSLSocketImpl.getSession()中实现的方式以及实现的方式,因此在使用Apache HTTP
Client时会遇到一些极端情况。

当使用Apache HTTP Client时,当不信任远程证书时也会抛出该异常,这通常会抛出“
sun.security.validator.ValidatorException: PKIX path building failed”。

发生这种情况的原因是因为Apache HTTP Client SSLSession在执行其他操作之前会尝试获取和对等证书。

提醒一下,有3种方法可以通过发起握手SSLSocket

  • 调用开始显式开始握手的startHandshake,或
  • 尝试在此套接字上读取或写入应用程序数据会导致隐式握手,或者
  • 如果当前没有有效的会话,则对getSession的调用尝试建立会话,并且隐式握手已完成。

这是3个示例,所有示例均针对具有不可信证书的主机(使用javax.net.ssl.SSLSocketFactory,而不是Apache)。

范例1:

    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();    SSLSocket sslSocket = (SSLSocket) ssf.createSocket("untrusted.host.example",            443);    sslSocket.startHandshake();

这将引发“ javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX path building failed”(如预期)。

范例2:

    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();    SSLSocket sslSocket = (SSLSocket) ssf.createSocket("untrusted.host.example",            443);    sslSocket.getInputStream().read();

这也会引发“ javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX path building failed”(如预期)。

范例3:

    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();    SSLSocket sslSocket = (SSLSocket) ssf.createSocket("untrusted.host.example",            443);    SSLSession sslSession = sslSocket.getSession();    sslSession.getPeerCertificates();

但是,这引发了javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

这是Apache
HTTP客户端AbstractVerifierorg.apache.http.conn.ssl.SSLSocketFactory在4.2.1版中使用的逻辑。更高版本基于发出的HTTPCLIENT-1346报告显式调用startHandshake()

最终,这似乎来自的实现sun.security.ssl.SSLSocketImpl.getSession(),该实现捕获了IOException在调用startHandshake(false)(内部方法)时抛出的潜在s
,而没有进一步抛出它。这可能是一个错误,尽管这不会对安全产生重大影响,因为SSLSocket无论如何仍将关闭。

范例4:

    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();    SSLSocket sslSocket = (SSLSocket) ssf.createSocket("untrusted.host.example",            443);    SSLSession sslSession = sslSocket.getSession();    // sslSession.getPeerCertificates();    sslSocket.getInputStream().read();

值得庆幸的是,javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX path buildingfailed每当您实际尝试使用它时,它仍然会抛出“ ” SSLSocket(在没有获得对等证书的情况下获得会话不会造成漏洞)。


如何解决这个问题

像其他任何不信任的证书问题一样,确保您使用的信任库包含必要的信任锚(例如,颁发要尝试验证的链的CA证书,或者可能是实际服务器)特殊情况证书)。

要解决此问题,您应该将CA证书(或者可能是服务器证书本身)导入到信任库中。你可以这样做:

  • 在您的JRE信任库中,通常是cacerts文件(不一定是最好的文件,因为这会影响使用该JRE的所有应用程序),
  • 在您的信任库的本地副本中(您可以使用-Djavax.net.ssl.trustStore=...选项进行配置),
  • 通过SSLContext为该连接创建一个特定对象。(有人建议使用不执行任何操作的信任管理器,但这会使您的连接容易受到MITM攻击。)

初步答案

javax.net.ssl.SSLPeerUnverifiedException:对等方未通过身份验证

这与信任证书无关,或者您必须创建一个自定义SSLContext:这是由于服务器根本不发送任何证书。

显然,该服务器未配置为正确支持TLS。这将失败(您将不会获得远程证书):

openssl s_client -tls1 -showcerts -connect

appserver.gtportalbase.com:443

但是,SSLv3似乎可以工作:

openssl s_client -ssl3 -showcerts -connect

appserver.gtportalbase.com:443

如果您知道谁在运行此服务器,则值得与他们联系以解决此问题。至少现在,服务器应该真正支持TLSv1。

同时,解决此问题的一种方法是创建您自己的问题并将org.apache.http.conn.ssl.SSLSocketFactory其用于与Apache
Http客户端的此连接。

该工厂需要创建一个SSLSocket照常使用的方法sslSocket.setEnabledProtocols(new String[]{"SSLv3"});,以在返回该套接字之前使用它来禁用TLS,否则默认情况下将启用它。

android httpclients 报 java.lang.VerifyError: org/apache/http/conn/ssl/DefaultHostnameVerifier

android httpclients 报 java.lang.VerifyError: org/apache/http/conn/ssl/DefaultHostnameVerifier

List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
                params.add(new BasicNameValuePair("ajax", "1"));

                String param = URLEncodedUtils.format(params, "UTF-8");
                String baseUrl = "http://www.xxx.com";
                Log.v("url", baseUrl+"?"+param);
                HttpGet httpGet = new HttpGet(baseUrl+"?"+param);
                CloseableHttpClient httpClient = HttpClients.createDefault();
                try {
                    CloseableHttpResponse response = httpClient.execute(httpGet);
                    HttpEntity httpEntity = response.getEntity();
                    TextView codeValueTV =(TextView) findViewById(R.id.codeValue);
                    codeValueTV.setText(response.getStatusLine()+"");
                    TextView contentTV =(TextView) findViewById(R.id.content);
                    contentTV.setText(EntityUtils.toString(httpEntity));
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

上面是代码详情。





Apache Curator与Zookeeper版本兼容性异常:org.apache.zookeeper.KeeperException$UnimplementedException: KeeperE

Apache Curator与Zookeeper版本兼容性异常:org.apache.zookeeper.KeeperException$UnimplementedException: KeeperE

ZooKeeper Version 3.4.x Compatibility

ZooKeeper 3.4.x is Now at end-of-life. Consequently, the latest versions of Curator have removed support for it. If you wish to use Curator with ZooKeeper 3.4.x you should pin to version 4.2.x of Curator. Curator 4.2.x supports ZooKeeper 3.4.x ensembles in a soft-compatibility mode. To use this mode you must exclude ZooKeeper when adding Curator to your dependency management tool.

Maven

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>4.2.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Gradle

compile('org.apache.curator:curator-recipes:$curatorVersion') {
  exclude group: 'org.apache.zookeeper', module: 'zookeeper'
}

You must add a dependency on ZooKeeper 3.4.x also.

Curator will detect which ZooKeeper library is in use and automatically set ZooKeeper 3.4 compatibility mode as needed. In this mode, all features not supported by 3.4 are disabled. It is up to your application code to "do the right thing" and not use these features. Use the isZk34CompatibilityMode() method to determine which mode Curator is using at runtime.

Testing With ZooKeeper 3.4.x

Note: If you wish to use Curator's TestingServer with ZooKeeper 3.4.x you must use the older version of it (in addition to the instructions above):

Maven

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-test</artifactId>
    <version>2.12.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
    <scope>test</scope>
</dependency>

Gradle

testCompile('org.apache.curator:curator-test:2.12.0') {
  exclude group: 'org.apache.zookeeper', module: 'zookeeper'
}


Curator 5.0 Breaking Changes

Curator 5.0 contains a few non-backward compatible/breaking changes from prevIoUs versions.

  • ZooKeeper 3.4.x is no longer supported (the associated Compatibility classes/methods have been removed). If you still need to use Curator with ZooKeeper 3.4.x you will need to use a prevIoUs version. Click here for details.
  • The old ListenerContainer classes have been removed so as not to leak Guava classes into Curator APIs. Instead use the new StandardListenerManager.
  • Exhibitor support has been removed.
  • ConnectionHandlingPolicy and related classes have been removed.
  • The Reaper and ChildReaper classes/recipes have been removed. You should use ZooKeeper container nodes instead.
  • newPersistentEphemeralNode() and newPathChildrenCache() were removed from GroupMember.
  • ServiceCacheBuilder<T> executorService(CloseableExecutorService executorService) was removed from ServiceCacheBuilder.
  • ServiceProviderBuilder<T> executorService(CloseableExecutorService executorService) was removed from ServiceProviderBuilder.
  • static boolean shouldRetry(int rc) was removed from RetryLoop.
  • static boolean isRetryException(Throwable exception) was removed from RetryLoop.
 

Apache DefaultHttpClient调用的结果为“ java.lang.RuntimeException:Stub!”

Apache DefaultHttpClient调用的结果为“ java.lang.RuntimeException:Stub!”

我正在全力投入Android开发。我有一个将与RESTful资源交互的项目,并且我试图弄清楚如何通过HTTP使用参数进行基本的GET。从我阅读的所有内容来看,共识似乎比HTTPURLConnection更偏爱HTTPClient。

我编写了一个包装器类,该包装器的方法负责实例化关键对象以使用HTTPClient发出请求:

public String get() {  
    String responseString = null;

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet();
    try {
        get.setURI(new URI(this.baseURL()));
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    HttpResponse response;

    try {
        response = client.execute(get);
        responseString = readResponse(response.getEntity());

        if(response != null) {
            System.out.println(responseString);
        }
    } catch(ClientProtocolException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }

    return responseString;

}

该行HttpClient client = new DefaultHttpClient();引发以下异常:

java.lang.RuntimeException: Stub!
at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:5)
at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:7)
at org.rcindustries.appmap.RestClient.get(RestClient.java:54)
at org.rcindustries.appmap.test.functional.RestClientTest.shouldReturnSomeJSon(RestClientTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

我为HttpClient看到的每个示例都使用类似的结构来执行GET和POST。与Android SDK捆绑在一起的Apache
Commons库是否与标准库明显不同?

Apache HttpClient临时错误:NoHttpResponseException

Apache HttpClient临时错误:NoHttpResponseException

我有一个Web服务正在接受XML的POST方法。它工作正常,然后在某个随机的时刻,它无法与服务器通信,并抛出message,并抛出IOException
The target server failed to respond。后续调用工作正常。

当我打了一些电话然后将应用程序闲置大约10-15分钟时,它就会发生。在此之后我进行的第一个调用将返回此错误。

我尝试了几件事…

我像这样设置重试处理程序

HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {            public boolean retryRequest(IOException e, int retryCount, HttpContext httpCtx) {                if (retryCount >= 3){                    Logger.warn(CALLER, "Maximum tries reached, exception would be thrown to outer block");                    return false;                }                if (e instanceof org.apache.http.NoHttpResponseException){                    Logger.warn(CALLER, "No response from server on "+retryCount+" call");                    return true;                }                return false;            }        };        httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);

但是此重试从未被调用过。(是的,我正在使用正确的instanceof子句)。在调试时,此类永远不会被调用。

我什至尝试设置HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),false);但没有用。有人可以建议我现在可以做什么吗?

重要事项 除了弄清楚为什么我会得到例外,我还有一个重要的担忧是为什么重试处理程序不在这里工作?

答案1

小编典典

由连接管理器保持活动状态的最有可能的持久连接变得陈旧。也就是说,目标服务器会在其连接空闲时关闭其末端的连接,而HttpClient无法对该事件做出反应,从而使连接半关闭或“陈旧”。通常这不是问题。HttpClient使用多种技术来验证从池中租借时的连接有效性。即使禁用了过时的连接检查并且使用了过时的连接来传输请求消息,请求执行通常也会在具有SocketException的写操作中失败,并会自动重试。但是,在某些情况下,写操作可以毫无例外地终止,随后的读操作将返回-1(流的结尾)。

解决此问题的最简单方法是将过期的连接和闲置了超过一段时间(例如,在池中闲置一分钟之后)之后空闲的连接驱逐出去。有关详细信息,请参见HttpClient教程的本节。

关于Apache HTTPClient SSLPeerUnverifiedException的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android httpclients 报 java.lang.VerifyError: org/apache/http/conn/ssl/DefaultHostnameVerifier、Apache Curator与Zookeeper版本兼容性异常:org.apache.zookeeper.KeeperException$UnimplementedException: KeeperE、Apache DefaultHttpClient调用的结果为“ java.lang.RuntimeException:Stub!”、Apache HttpClient临时错误:NoHttpResponseException等相关知识的信息别忘了在本站进行查找喔。

本文标签: