Java 类org.apache.http.conn.ssl.DefaultHostnameVerifier 实例源码

项目:safecharge-java    文件:SafechargeClientBuilder.java   
/**
 * Sets a Safecharge's default  {@link LayeredConnectionSocketFactory} object to set connection properties,
 * such as supported SSL Protocols, hostname verifier, etc(needed to create a https connection).
 *
 * @return this object
 */
public SafechargeClientBuilder setDefaultSSLSocketFactory() {
    SSLContext sslContext = SSLContexts.createDefault();
    String[] javaSupportedProtocols = sslContext.getSupportedSSLParameters()
            .getProtocols();

    List<String> supportedProtocols = new ArrayList<>();
    for (String SERVER_SUPPORTED_SSL_PROTOCOL : SERVER_SUPPORTED_SSL_PROTOCOLS) {
        for (String javaSupportedProtocol : javaSupportedProtocols) {
            if (SERVER_SUPPORTED_SSL_PROTOCOL.equals(javaSupportedProtocol)) {
                supportedProtocols.add(SERVER_SUPPORTED_SSL_PROTOCOL);
            }
        }
    }

    if (!supportedProtocols.isEmpty()) {
        sslSocketFactory =
                new SSLConnectionSocketFactory(sslContext, supportedProtocols.toArray(new String[]{}), null, new DefaultHostnameVerifier());
    } else {
        throw new UnsupportedOperationException("Your Java version doesn't support any of the server supported SSL protocols: " + Arrays.toString(
                SERVER_SUPPORTED_SSL_PROTOCOLS));
    }
    return this;
}
项目:calcite-avatica    文件:AvaticaCommonsHttpClientImplTest.java   
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
项目:weixin-java-tools-for-JDK6    文件:WxMpServiceImpl.java   
private void initHttpClient() {
  ApacheHttpClientBuilder apacheHttpClientBuilder = this.configStorage
      .getApacheHttpClientBuilder();
  if (null == apacheHttpClientBuilder) {
    apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get();
  }

  apacheHttpClientBuilder.httpProxyHost(this.configStorage.getHttpProxyHost())
      .httpProxyPort(this.configStorage.getHttpProxyPort())
      .httpProxyUsername(this.configStorage.getHttpProxyUsername())
      .httpProxyPassword(this.configStorage.getHttpProxyPassword());

  if (this.configStorage.getSSLContext() != null) {
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        this.configStorage.getSSLContext(), new String[] { "TLSv1" }, null,
        new DefaultHostnameVerifier());
    apacheHttpClientBuilder.sslConnectionSocketFactory(sslsf);
  }

  if (this.configStorage.getHttpProxyHost() != null && this.configStorage.getHttpProxyPort() > 0) {
    this.httpProxy = new HttpHost(this.configStorage.getHttpProxyHost(), this.configStorage.getHttpProxyPort());
  }

  this.httpClient = apacheHttpClientBuilder.build();
}
项目:navigator-sdk    文件:SSLUtilsTest.java   
@Test
public void testGetHostnameVerifier() {
  // Default
  HostnameVerifier verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof DefaultHostnameVerifier);

  // Override
  config.setOverrideHostnameVerifier(new TestHostnameVerifier());
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof TestHostnameVerifier);

  // Disabled
  config.setDisableSSLValidation(true);
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof NoopHostnameVerifier);
}
项目:restendpoint    文件:RestEndpoints.java   
/**
     * Adds Keystore for SSL
     *
     * @param keyStore     KeyStore input stream
     * @param keyStorePass KeyStore password
     * @return This builder
     */
    public final Builder withSsl(InputStream keyStore, String keyStorePass) {
        SSLContext sslcontext;
        try {
            sslcontext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(IOUtils.loadKeyStore(keyStore, keyStorePass), null)
                    .build();
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to load trust store", e);
        }

        /*
         * Unreal magic, but we can't use
* org.apache.http.conn.ssl.SSLConnectionSocketFactory
* .BROWSER_COMPATIBLE_HOSTNAME_VERIFIER here due to some problems
* related to classloaders. Initialize host name verifier explicitly
*/
        SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(
                sslcontext,
                new DefaultHostnameVerifier());
        httpClientBuilder.setSSLStrategy(sslSessionStrategy);

        return this;
    }
项目:apiman    文件:DefaultEsClientFactory.java   
/**
 * @param httpConfig
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig) {
    try {
        String clientKeystorePath = getConfig().get("client-keystore");
        String clientKeystorePassword = getConfig().get("client-keystore.password");
        String trustStorePath = getConfig().get("trust-store");
        String trustStorePassword = getConfig().get("trust-store.password");

        SSLContext sslContext = SSLContext.getInstance("TLS");
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), null);
        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:apiman    文件:DefaultESClientFactory.java   
/**
 * @param httpConfig
 * @param config 
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client-keystore");
        String clientKeystorePassword = config.get("client-keystore.password");
        String trustStorePath = config.get("trust-store");
        String trustStorePassword = config.get("trust-store.password");

        SSLContext sslContext = SSLContext.getInstance("TLS");
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), null);
        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:cas-5.1.0    文件:CasCoreHttpConfiguration.java   
@ConditionalOnMissingBean(name = "hostnameVerifier")
@Bean
public HostnameVerifier hostnameVerifier() {
    if (casProperties.getHttpClient().getHostNameVerifier().equalsIgnoreCase("none")) {
        return NoopHostnameVerifier.INSTANCE;
    }
    return new DefaultHostnameVerifier();
}
项目:Wechat-Group    文件:WxMpPayServiceImpl.java   
private String executeWithKey(String url, String requestStr) throws WxErrorException {
  try {
    SSLContext sslContext = getConfig().getSslContext();
    if (null == sslContext) {
      throw new IllegalArgumentException("请先初始化配置类(即WxMpConfigStorage的实现类)中的SSLContext!");
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null,
      new DefaultHostnameVerifier());

    HttpPost httpPost = new HttpPost(url);
    if (this.wxMpService.getHttpProxy() != null) {
      httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
    }

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {
      httpPost.setEntity(new StringEntity(new String(requestStr.getBytes("UTF-8"), "ISO-8859-1")));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        this.log.debug("\n[URL]:  {}\n[PARAMS]: {}\n[RESPONSE]: {}", url, requestStr, result);
        return result;
      }
    } finally {
      httpPost.releaseConnection();
    }
  } catch (Exception e) {
    this.log.error("\n[URL]:  {}\n[PARAMS]: {}\n[EXCEPTION]: {}", url, requestStr, e.getMessage());
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg(e.getMessage()).build(), e);
  }
}
项目:qonduit    文件:HttpClient.java   
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
项目:timely    文件:HttpClient.java   
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
项目:burp-extension    文件:SSLConnectionSocketFactoryFactory.java   
/**
 * Creates a new SSLConnectionSocketFactory with the behavior described in
 * {@link #getFactory(String)}. Instead of returning, this method registers
 * the factory instance to the <code>factoriesByHost<code> map, as well as
 * registering its <code>ExtraCertManager</code> to the
 * <code>certManagersByHost</code> map. The cert manager registration is
 * important in order to detect and purge trusted certificates on a per-host
 * basis.
 * 
 * @param host
 * @param burpExtender
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static void initializeFactory(String host, BurpExtender burpExtender) throws IOException, GeneralSecurityException {
    // set up the certificate management
    File managedKeyStoreFile = getTrustStoreForHost(host);
    ExtraCertManager certManager = new SingleExtraCertManager(managedKeyStoreFile, "u9lwIfUpaN");

    // get the default hostname verifier that gets used by the modified one
    // and the invalid cert dialog
    HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();


    InvalidCertificateStrategy invalidCertStrat = new InvalidCertificateDialogStrategy(defaultHostnameVerifier, host, burpExtender);

    /*
     * Set up a composite trust manager that uses the default trust manager
     * before delegating to the "reloadable" trust manager that allows users
     * to accept invalid certificates.
     */
    List<X509TrustManager> trustManagersForComposite = new LinkedList<>();
    X509TrustManager systemTrustManager = getDefaultTrustManager();
    ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, invalidCertStrat);
    trustManagersForComposite.add(systemTrustManager);
    trustManagersForComposite.add(customTrustManager);
    X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);

    // setup the SSLContext using the custom trust manager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    // the actual hostname verifier that will be used with the socket
    // factory
    Set<String> allowedHosts = new HashSet<>();
    allowedHosts.add(host);
    HostnameVerifier modifiedHostnameVerifier = new HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts);

    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier);
    // Register the `factory` and the `customTrustManager` under the given
    // `host`
    factoriesByHost.put(host, factory);
    customTrustByHost.put(host, customTrustManager);
}
项目:lavaplayer    文件:HttpClientTools.java   
private static Registry<ConnectionSocketFactory> createConnectionSocketFactory() {
  HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault());
  ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext != null ? sslContext :
      SSLContexts.createDefault(), hostnameVerifier);

  return RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslSocketFactory)
      .build();
}
项目:navigator-sdk    文件:SSLUtils.java   
/**
 * If SSL validation is disabled then return a HostnameVerifier that accepts
 * everything. Otherwise, return the override HostnameVerifier in the config
 * if specified, or return a new DefaultHostnameVerifier
 *
 * @param config
 */
public static HostnameVerifier getHostnameVerifier(ClientConfig config) {
  if (config.isDisableSSLValidation()) {
    return new NoopHostnameVerifier();
  }
  if (config.getOverrideHostnameVerifier() == null) {
    return new DefaultHostnameVerifier();
  } else {
    return config.getOverrideHostnameVerifier();
  }
}
项目:oap    文件:Client.java   
private HttpAsyncClientBuilder initialize() {
    try {
        final PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(
            new DefaultConnectingIOReactor( IOReactorConfig.custom()
                .setConnectTimeout( connectTimeout )
                .setSoTimeout( readTimeout )
                .build() ),
            RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register( "http", NoopIOSessionStrategy.INSTANCE )
                .register( "https",
                    new SSLIOSessionStrategy( certificateLocation != null ?
                        createSSLContext( certificateLocation, certificatePassword )
                        : SSLContexts.createDefault(),
                        split( System.getProperty( "https.protocols" ) ),
                        split( System.getProperty( "https.cipherSuites" ) ),
                        new DefaultHostnameVerifier( PublicSuffixMatcherLoader.getDefault() ) ) )
                .build() );

        connManager.setMaxTotal( maxConnTotal );
        connManager.setDefaultMaxPerRoute( maxConnPerRoute );

        return ( certificateLocation != null ?
            HttpAsyncClients.custom()
                .setSSLContext( createSSLContext( certificateLocation, certificatePassword ) )
            : HttpAsyncClients.custom() )
            .setMaxConnPerRoute( maxConnPerRoute )
            .setConnectionManager( connManager )
            .setMaxConnTotal( maxConnTotal )
            .setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE )
            .setDefaultRequestConfig( RequestConfig
                .custom()
                .setRedirectsEnabled( redirectsEnabled )
                .setCookieSpec( cookieSpec )
                .build() )
            .setDefaultCookieStore( basicCookieStore );
    } catch( IOReactorException e ) {
        throw new UncheckedIOException( e );
    }
}
项目:bricklink    文件:BrickLinkClient.java   
public BrickLinkClient(String consumerKey, String consumerSecret, String tokenValue, String tokenSecret) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    super();
    consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    consumer.setTokenWithSecret(tokenValue, tokenSecret);
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, new DefaultHostnameVerifier());
    client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
项目:Reer    文件:HttpClientConfigurer.java   
private void configureSslSocketConnectionFactory(HttpClientBuilder builder, SslContextFactory sslContextFactory) {
    builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextFactory.createSslContext(), new DefaultHostnameVerifier(null)));
}
项目:weixin-java-tools    文件:WxPayServiceApacheHttpImpl.java   
@Override
protected String post(String url, String requestStr, boolean useKey) throws WxPayException {
  try {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    if (useKey) {
      SSLContext sslContext = this.getConfig().getSslContext();
      if (null == sslContext) {
        sslContext = this.getConfig().initSSLContext();
      }

      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
        new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
      httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    HttpPost httpPost = new HttpPost(url);

    httpPost.setConfig(RequestConfig.custom()
      .setConnectionRequestTimeout(this.getConfig().getHttpConnectionTimeout())
      .setConnectTimeout(this.getConfig().getHttpConnectionTimeout())
      .setSocketTimeout(this.getConfig().getHttpTimeout())
      .build());

    if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
      && this.getConfig().getHttpProxyPort() > 0) {
      // 使用代理服务器 需要用户认证的代理服务器
      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(
        new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
        new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
      httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    try (CloseableHttpClient httpclient = httpClientBuilder.build()) {
      httpPost.setEntity(new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
        wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
        return responseString;
      }
    } finally {
      httpPost.releaseConnection();
    }
  } catch (Exception e) {
    this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
    wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
    throw new WxPayException(e.getMessage(), e);
  }
}
项目:substitution-schedule-parser    文件:BaseParser.java   
public CustomHostnameVerifier(String host) {
    this.host = host;
    this.defaultHostnameVerifier = new DefaultHostnameVerifier();
}
项目:purecloud-iot    文件:ClientCustomPublicSuffixList.java   
public final static void main(String[] args) throws Exception {

        // Use PublicSuffixMatcherLoader to load public suffix list from a file,
        // resource or from an arbitrary URL
        PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(
                new URL("https://publicsuffix.org/list/effective_tld_names.dat"));

        // Please use the publicsuffix.org URL to download the list no more than once per day !!!
        // Please consider making a local copy !!!

        DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

        RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
        Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
                .register(CookieSpecs.DEFAULT, cookieSpecProvider)
                .register(CookieSpecs.STANDARD, cookieSpecProvider)
                .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)
                .build();

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLHostnameVerifier(hostnameVerifier)
                .setDefaultCookieSpecRegistry(cookieSpecRegistry)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://httpbin.org/");

            System.out.println("executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
项目:geoevent-datastore-proxy    文件:DataStoreProxyHostnameVerifier.java   
DataStoreProxyHostnameVerifier(Collection<X509Certificate>  trustedCerts)
{
    this.trustedCerts = trustedCerts;
    this.verifier = new DefaultHostnameVerifier();
}
项目:mandrel    文件:ApacheHttpRequester.java   
public void init() {

        available = new Semaphore(maxParallel(), true);

        SSLContext sslContext = SSLContexts.createSystemDefault();
        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

        Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();

        DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
            @Override
            public InetAddress[] resolve(final String host) throws UnknownHostException {
                if (host.equalsIgnoreCase("localhost")) {
                    return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                } else {
                    return new InetAddress[] { nameResolver().resolve(host) };
                }
            }
        };

        // Create a connection manager with custom configuration.
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(sessionStrategyRegistry, dnsResolver);

        // Create message constraints
        MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount).setMaxLineLength(maxLineLength).build();

        // Create connection configuration
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();
        connManager.setDefaultConnectionConfig(connectionConfig);

        // Configure total max or per route limits for persistent connections
        // that can be kept in the pool or leased by the connection manager.
        connManager.setMaxTotal(maxPersistentConnections());
        connManager.setDefaultMaxPerRoute(maxPersistentConnections());

        // TODO
        // Use custom credentials provider if necessary.
        // CredentialsProvider credentialsProvider = new
        // BasicCredentialsProvider();

        // Create global request configuration
        defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects()).setSocketTimeout(socketTimeout())
                .setConnectTimeout(connectTimeout()).setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build();

        // Create an HttpClient with the given custom dependencies and
        // configuration.
        client = HttpClients.custom().setConnectionManager(connManager)
        // .setDefaultCredentialsProvider(credentialsProvider)
                .setDefaultRequestConfig(defaultRequestConfig).build();
    }
项目:uw-android    文件:ClientCustomPublicSuffixList.java   
public final static void main(String[] args) throws Exception {

        // Use PublicSuffixMatcherLoader to load public suffix list from a file,
        // resource or from an arbitrary URL
        PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(
                new URL("https://publicsuffix.org/list/effective_tld_names.dat"));

        // Please use the publicsuffix.org URL to download the list no more than once per day !!!
        // Please consider making a local copy !!!

        DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);

        RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
        Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
                .register(CookieSpecs.DEFAULT, cookieSpecProvider)
                .register(CookieSpecs.STANDARD, cookieSpecProvider)
                .register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)
                .build();

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLHostnameVerifier(hostnameVerifier)
                .setDefaultCookieSpecRegistry(cookieSpecRegistry)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://remotehost/");

            System.out.println("executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
项目:skadi    文件:DownloadService.java   
public DownloadService(final String remoteUrl, final File localFile) {
    httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(new DefaultHostnameVerifier()).build();

    this.remoteUrl = remoteUrl;
    this.localFile = localFile;
}
项目:scale.commons    文件:HttpBuilder.java   
/**
 * Enables/disables hostname verification during SSL handshakes.
 * <p/>
 * If verification is enabled, the SSL handshake will only succeed if the
 * URL's hostname and the server's identification hostname match.
 *
 * @param shouldVerify
 *            Enable (<code>true</code>) or disable (<code>false</code>).
 * @return
 */
public HttpBuilder verifyHostname(boolean shouldVerify) {
    HostnameVerifier sslHostnameVerifier = shouldVerify ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    this.clientBuilder.setSSLHostnameVerifier(sslHostnameVerifier);
    return this;
}
项目:saki-monkey    文件:AbstractMandrillClient.java   
/**
 * 
 * @return default HostnameVerifier object
 */
protected HostnameVerifier createHostnameVerifier(){
    return new DefaultHostnameVerifier();
}