Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.

Prototype

X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLConnectionSocketFactory BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    /**/*from   w w  w . j  a  v a  2 s .co m*/
     * ?PKCS12? ?-- API 
     */
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    /**
     * ?
     */
    //ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ "");
    //      FileInputStream instream = new FileInputStream(new File("D:/Program Files/MyEclipse 6.5/workspace/weidian/WebRoot/cer/apiclient_cert.p12"));//P12
    FileInputStream instream = new FileInputStream(
            ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + WxpayConfig.cert_path));
    try {
        /**
         * ?
         * MCHID
         * */
        keyStore.load(instream, WxpayConfig.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxpayConfig.mch_id.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 httpost = new HttpPost(url); // ??

        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:nl.eveoh.mytimetable.apiclient.service.MyTimetableHttpClientBuilderImpl.java

private SSLConnectionSocketFactory createSslSocketFactory(Configuration configuration) {
    X509HostnameVerifier verifier;
    if (configuration.isApiSslCnCheck()) {
        verifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    } else {// ww w  . ja va  2s  .c o  m
        verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    }

    return new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(), verifier);
}

From source file:org.ops4j.pax.url.mvn.internal.HttpClients.java

private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) {
    boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates",
            false);//from w  ww . j  a  v  a  2 s  .  com
    boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true);
    int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20);
    int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40);

    String sslProtocolsStr = getProperty(resolver, "https.protocols", null);
    String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null);
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

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

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }

    boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false);
    int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1);
    boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS,
            false);
    boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true);
    //        int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 );
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(soKeepAlive) // default false
            .setSoLinger(soLinger) // default -1
            .setSoReuseAddress(soReuseAddress) // default false
            .setTcpNoDelay(soTcpNoDelay) // default true
            .setSoTimeout(0) // default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout()
            // this value is not used
            .build();
    connManager.setDefaultSocketConfig(socketConfig);

    int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192);
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(bufferSize) // default 8192
            .setFragmentSizeHint(bufferSize) // default 'buffer size'
            .build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    return connManager;
}

From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

public HostResolvedSSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
        final String[] supportedProtocols, final String[] supportedCipherSuites,
        final X509HostnameVerifier hostnameVerifier) {
    this.socketfactory = Args.notNull(socketfactory, "SSL socket factory");
    this.supportedProtocols = supportedProtocols;
    this.supportedCipherSuites = supportedCipherSuites;
    this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier
            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
}

From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

public HostResolvedSSLConnectionSocketFactory(final SSLContext sslContext) {
    this(sslContext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//from   ww  w . j av a 2s .  c om

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {/*from  w  w  w.  j av a  2s.  c  om*/
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}