Java Code Examples for org.apache.http.conn.ssl.SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

The following examples show how to use org.apache.http.conn.ssl.SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * https请求
 * 
 * @param certificatePath
 * @param secretKey
 * @return
 */
@SuppressWarnings("deprecation")
public static CloseableHttpClient createSSL(String certificatePath, String secretKey) {
    KeyStore keyStore = null;
    CloseableHttpClient httpclient = null;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(certificatePath));
        try {
            keyStore.load(instream, secretKey.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, secretKey.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return httpclient;
}
 
Example 2
Source File: AbstractWebUtils.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
/**
 * 利用证书请求微信
 *
 * @param certPath 证书路径
 * @param passwd   证书密码
 * @param uri      请求地址
 * @param entity   请求体xml内容
 * @param encording 编码格式
 * @throws Exception 异常
 * @return 得到的结果
 */
public static String post(String certPath, String passwd, String uri, InputStreamEntity entity,
                          String encording) throws Exception {
    String result = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(certPath));
    try {
        keyStore.load(instream, passwd.toCharArray());
    } finally {
        instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"},
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpPost = new HttpPost(uri);
        entity.setContentEncoding(encording);
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
        result = consumeResponse(httpResponse, encording);
    } finally {
        httpclient.close();
    }
    return result;
}
 
Example 3
Source File: ApacheConnectionManagerFactory.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostNameVerifier
        (HttpClientSettings options) {
    // TODO Need to find a better way to handle these deprecations.
    return options.useBrowserCompatibleHostNameVerifier()
            ? SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
}
 
Example 4
Source File: HttpsRequest.java    From pay with Apache License 2.0 5 votes vote down vote up
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
        try {
            keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, config.getCertPassword().toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();

        hasInit = true;
    }
 
Example 5
Source File: HttpsRequest.java    From pay with Apache License 2.0 5 votes vote down vote up
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
        try {
            keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, config.getCertPassword().toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();

        hasInit = true;
    }
 
Example 6
Source File: WxMpServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
  this.wxMpConfigStorage = wxConfigProvider;

  String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
  int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
  String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
  String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();

  final HttpClientBuilder builder = HttpClients.custom();
  if (StringUtils.isNotBlank(http_proxy_host)) {
    // 使用代理服务器
    if (StringUtils.isNotBlank(http_proxy_username)) {
      // 需要用户认证的代理服务器
      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(http_proxy_host, http_proxy_port),
          new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
      builder
          .setDefaultCredentialsProvider(credsProvider);
    } else {
      // 无需用户认证的代理服务器
    }
    httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
  }
  if (wxConfigProvider.getSSLContext() != null){
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        wxConfigProvider.getSSLContext(),
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    builder.setSSLSocketFactory(sslsf);
  }
  httpClient = builder.build();
}
 
Example 7
Source File: TaxiiHandler.java    From metron with Apache License 2.0 4 votes vote down vote up
private static HttpClient buildClient(URL proxy, String username, String password) throws Exception
{
  HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

  // Create an Apache HttpClientBuilder to be customized by the command line arguments.
  HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

  // Proxy
  if (proxy != null) {
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
    builder.setProxy(proxyHost);
  }

  // Basic authentication. User & Password
  if (username != null ^ password != null) {
    throw new Exception("'username' and 'password' arguments are required to appear together.");
  }


  // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
  SSLContextBuilder ssbldr = new SSLContextBuilder();
  ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);


  Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", new PlainConnectionSocketFactory())
      .register("https", sslsf)
      .build();


  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
  cm.setMaxTotal(20);//max connection

  System.setProperty("jsse.enableSNIExtension", "false"); //""
  CloseableHttpClient httpClient = builder
      .setSSLSocketFactory(sslsf)
      .setConnectionManager(cm)
      .build();

  client.setHttpclient(httpClient);
  return client;
}