本文介绍了Apache HttpClient 获取服务器证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在请求后使用 Apache HttpClient 获取经过身份验证的服务器的 SSL 证书 - 只是服务器端 request.getAttribute("javax.servlet.request.X509Certificate") 的对应物?

Is there a way to get the SSL certificate of the authenticated server using Apache HttpClient after the request - just the counterpart to request.getAttribute("javax.servlet.request.X509Certificate") on the server side?

推荐答案

好吧,这在某些方面有点元,我希望以一种适用于任何连接管理器的方式来做这件事.我假设您在最新的 HttpClient (4.2) 上运行

Ok this is a bit meta in some respects and I'm hopefully doing this in a fashion that will work with any connection manager. I'm assuming you're running on the latest HttpClient (4.2)

因此,您需要做的是向客户端添加一个 HttpResponseInterceptor.

So, what you will have to do is add an HttpResponseInterceptor to the client.

((AbstractHttpClient)client).addResponseInterceptor(new HttpResponseInterceptor() {
    @Override
    public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
        HttpRoutedConnection routedConnection= (HttpRoutedConnection)context.getAttribute(ExecutionContext.HTTP_CONNECTION);
        if( routedConnection.isSecure() ) {
            Certificate[] certificates= routedConnection.getSSLSession().getPeerCertificates();
            // Assume that PEER_CERTIFICATES is a constant you've defined
            context.setAttribute(PEER_CERTIFICATES, certificates);
        }
    }
});

一旦完成,通过此客户端发出的任何请求将检查连接是否标记为安全",然后尝试获取对等证书.

Once that is done, any request made through this client will check to see if the connection is marked as 'secure' and then attempt to get the peer certificates.

在此示例中,我只是放入与对等连接关联的整个证书数组.

In this example, I'm just putting in the entire array of certificates that were associated with the peer connection.

此时,要执行您将执行以下操作:

At this point, to execute you will do something similar to the following:

HttpContext context= new BasicHttpContext();
HttpGet get= new HttpGet(....);
client.execute(get, context);
// should contain the array of Certificate - these are more likely X509Certificate instances
Certificate[] peerCertificates= (Certificate[])context.getAttribute(PEER_CERTIFICATES);certificates
// do whatever logic to complete and consume the request

希望这能满足您的需求 - 如果有人对此有任何建议,我们将不胜感激.

Hopefully that will get what you need - if anyone has suggestions beyond this they'd be appreciated.

EDIT 这也可以作为 HttpRequestInterceptor 来完成,并且与已经建立的连接具有相同的效果.

EDIT This can also be done as a HttpRequestInterceptor and have the same effect as the connection is already established.

这篇关于Apache HttpClient 获取服务器证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:55