HttpRoutePlanner - How does it work with an HTTPS Proxy

て烟熏妆下的殇ゞ 提交于 2019-12-05 12:24:19

I was able to make the Apache HttpClient 4.x work with the HTTPS proxy. The SSLPeerUnverifiedException that I mentioned in the question was thrown because I was not trusting the Proxy Server's certificate. Once this is taken care of, then connections to HTTPS End-Sites worked as expected.

For connections to HTTP end-sites, I had to use my own HttpRoutePlanner to make it work. Here's the code with the explanations -

DefaultHttpClient dhc = new DefaultHttpClient();
HttpHost proxy = new HttpHost("192.168.2.3", 8181, "https");
dhc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

SchemeSocketFactory factory = null;
try {
    factory = new SSLSocketFactory(new SimpleTrustStrategy()); //Trust All strategy
} catch (GeneralSecurityException e1) {
    e1.printStackTrace();
}
Scheme https = new Scheme("https", 443, factory);
dhc.getConnectionManager().getSchemeRegistry().register(https);

HttpGet request = new HttpGet("http://en.wikipedia.org/wiki/Main_Page");    

try {
    HttpHost host = determineTarget(request);

    if(host.getSchemeName().equalsIgnoreCase("http")){
        dhc.setRoutePlanner(new MyRoutePlanner());
    }

} catch (ClientProtocolException e1) {
    e1.printStackTrace();
}

The implementation of MyRoutePlanner is below -

public class MyRoutePlanner implements HttpRoutePlanner {
    @Override
    public HttpRoute determineRoute(HttpHost target, HttpRequest request,
            HttpContext context) throws HttpException {
        return new HttpRoute(target, null
                , new HttpHost("192.168.2.3", 8181, "https")
                , true, TunnelType.PLAIN, LayerType.PLAIN); //Note: true
    }
}

To make the HttpClient talk to a HTTP End-site through an HTTPS Proxy, the route should be secure, but there should not be any Tunnelling or Layering.

Apache HttpClient 4.x only supports SSL via proxy only by connection tunneling. It does not support HTTPS proxies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!