zoukankan      html  css  js  c++  java
  • HttpClient代码设置代理

    由于对接faceBook接口,本地测试时候要设置代理才能调试。

    (http和https通用)

    public  SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
            SSLContext sc = SSLContext.getInstance("SSLv3");
    
            // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) throws CertificateException {
                }
    
                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) throws CertificateException {
                }
    
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
    
            sc.init(null, new TrustManager[]{trustManager}, null);
            return sc;
        }
    
        public static HttpClientBuilder proxy(String hostOrIP, int port){
            // 依次是代理地址,代理端口号,协议类型
            HttpHost proxy = new HttpHost(hostOrIP, port, "http");
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            return HttpClients.custom().setRoutePlanner(routePlanner);
        }
    SSLContext sslcontext = null;
    try {
    sslcontext = createIgnoreVerifySSL();
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    } catch (KeyManagementException e) {
    e.printStackTrace();
    }
    // 设置协议http和https对应的处理socket链接工厂的对象
           Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
             .register("http", PlainConnectionSocketFactory.INSTANCE)
             .register("https", new SSLConnectionSocketFactory(sslcontext))
             .build();
              PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
              HttpClients.custom().setConnectionManager(connManager);
     //创建自定义的httpclient对象,代理地址和端口
            CloseableHttpClient httpClient = proxy("127.0.0.1", 2222).setConnectionManager(connManager).build();
  • 相关阅读:
    Yii2 composer报错处理
    bootstrap元素居中
    前端面试题
    control-lable的用法
    jenkins持续集成搭建
    gitlab管理平台搭建
    mysql8.0.11安装
    nexus私服搭建、配置、使用
    mysql5.7.22安装
    nginx配置阿里云免费ssl证书实现https化
  • 原文地址:https://www.cnblogs.com/xiaoheis/p/9300128.html
Copyright © 2011-2022 走看看