Apache HttpClient获取服务器证书 [英] Apache HttpClient get server certificate

查看:149
本文介绍了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);
        }
    }
});

完成后,通过此客户端发出的任何请求都将检查连接是否标记为'secure'然后尝试获取对等证书。

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.

编辑这也可以作为HttpRequestInterceptor完成,并且具有与已建立连接相同的效果。

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆