List of usage examples for org.apache.http.conn.ssl SSLContexts custom
public static SSLContextBuilder custom()
From source file:com.jiuyi.qujiuyi.common.util.WxRefundSSL.java
public final static String post(String entity, String mch_id, Integer clientType) throws Exception { try {//from w ww .j a va2s .c o m KeyStore keyStore = KeyStore.getInstance("PKCS12"); // FileInputStream instream = new FileInputStream(new // File("D:\\apiclient_cert.p12")); FileInputStream instream = null; if (clientType == 0) { instream = new FileInputStream(new File(SysCfg.getString("apiclient.ssl"))); } else { instream = new FileInputStream(new File(SysCfg.getString("apiclient.app.ssl"))); } try { keyStore.load(instream, mch_id.toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build(); sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception e) { e.printStackTrace(); } CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); String result = ""; try { HttpPost post = new HttpPost(SysCfg.getString("weixin.refund")); post.setEntity(new StringEntity(entity)); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity resp = response.getEntity(); if (resp != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resp.getContent())); String line = null; while ((line = bufferedReader.readLine()) != null) { result += line; } } EntityUtils.consume(resp); } finally { response.close(); } } finally { httpclient.close(); } return result; }
From source file:com.weitaomi.systemconfig.wechat.ClientCustomSSL.java
public static String connectKeyStore(String url, String xml, String path, int flag) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); File file = LoadFileFactory.getFile(path); char[] arr = null; if (flag == 0) { arr = WechatConfig.MCHID.toCharArray(); }/*from w w w . ja va 2 s . c o m*/ if (flag == 1) { arr = WechatConfig.MCHID_OFFICIAL.toCharArray(); } FileInputStream instream = new FileInputStream(file); try { keyStore.load(instream, arr); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, arr).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(); StringEntity entityRequest = new StringEntity(xml, "utf-8"); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entityRequest); // httpPost.setHeader("Content-Type", "application/json");//; charset=utf-8 HttpResponse response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException(""); } HttpEntity resEntity = response.getEntity(); InputStream inputStream = resEntity.getContent(); return HttpRequestUtils.readInstream(inputStream, "UTF-8"); }
From source file:org.jwebsocket.sso.HTTPSupport.java
/** * * @param aURL//from w ww . j a va 2 s .c om * @param aMethod * @param aHeaders * @param aPostBody * @param aTimeout * @return */ public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody, long aTimeout) { if (mLog.isDebugEnabled()) { mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: " + aHeaders + ", Body: " + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'" : "[null]")); } String lResponse = "{\"code\": -1, \"msg\": \"undefined\""; try { KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); lTrustStore.load(null, null); // Trust own CA and all self-signed certs SSLContext lSSLContext = SSLContexts.custom() .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build(); HttpUriRequest lRequest; if ("POST".equals(aMethod)) { lRequest = new HttpPost(aURL); ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8"))); } else { lRequest = new HttpGet(aURL); } for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) { lRequest.setHeader(lEntry.getKey(), lEntry.getValue()); } // System.out.println("Executing request " + lRequest.getRequestLine()); // Create a custom response handler ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse lResponse) throws ClientProtocolException, IOException { int lStatus = lResponse.getStatusLine().getStatusCode(); HttpEntity lEntity = lResponse.getEntity(); return lEntity != null ? EntityUtils.toString(lEntity) : null; // if (lStatus >= 200 && lStatus < 300) { // HttpEntity entity = lResponse.getEntity(); // return entity != null ? EntityUtils.toString(entity) : null; // } else { // throw new ClientProtocolException("Unexpected response status: " + lStatus); // } } }; long lStartedAt = System.currentTimeMillis(); lResponse = lHTTPClient.execute(lRequest, lResponseHandler); if (mLog.isDebugEnabled()) { mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '" + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'"); } return lResponse; } catch (Exception lEx) { String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: " + lEx.getMessage() + "\"}"; mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg); lResponse = lMsg; return lResponse; } }
From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java
public static String doRefund(String url, String data) throws Exception { /**/*from w ww . j ava2 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:org.hawkular.component.pinger.Pinger.java
public Pinger() throws Exception { SSLContext tmpSslContext;//from w ww . j ava2 s. co m try { SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); tmpSslContext = builder.build(); } catch (Exception e) { tmpSslContext = null; } sslContext = tmpSslContext; }
From source file:io.pivotal.xd.chaoslemur.infrastructure.StandardDirectorUtils.java
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password)); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS() .build();/*from w w w. ja v a 2 s . c o m*/ SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling() .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build(); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); restTemplate.getInterceptors().addAll(interceptors); return restTemplate; }
From source file:org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmHttpsConfiguration.java
@Bean @Qualifier("hgmRestTemplate") public RestTemplate getHgmHttpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS() .build();/*w ww . ja v a 2 s . co m*/ SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword())); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(connectionFactory) .setDefaultCredentialsProvider(credentialsProvider).build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(requestFactory); }
From source file:com.github.tomakehurst.wiremock.http.HttpClientFactory.java
private static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings) { try {//from w w w . jav a2s . co m KeyStore trustStore = trustStoreSettings.loadStore(); return SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray()).useTLS().build(); } catch (Exception e) { return throwUnchecked(e, SSLContext.class); } }
From source file:com.vmware.bdd.cli.http.HttpClientProvider.java
@Bean(name = SECURE_HTTP_CLIENT) @Qualifier(SECURE_HTTP_CLIENT)//from www .j a v a 2 s . c om public HttpClient secureHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { SSLContext sslContext = SSLContexts.custom().useTLS().build(); sslContext.init(null, new TrustManager[] { trustManager }, null); String[] supportedProtocols = cliProperties.getSupportedProtocols(); String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites(); String hostnameVerifier = cliProperties.getHostnameVerifier(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols)); LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites)); LOGGER.debug("hostname verifier: " + hostnameVerifier); } SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, getHostnameVerifier(hostnameVerifier)); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); cm.setMaxTotal(20); cm.setDefaultMaxPerRoute(10); // HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http"); // HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build(); HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); return client1; }
From source file:cycronix.ctlib.CThttp.java
private void enableSelfSigned() { try {//from w ww. ja v a 2 s. co m httpclient = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory( SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())) .build(); } catch (Exception e) { System.err.println("Exception on TrustSelfSigned"); } }