List of usage examples for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier
public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier)
From source file:com.gft.unity.android.AndroidIO.java
public void createHttpClients() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, KeyManagementException, UnrecoverableKeyException { SSLSocketFactory socketFactory; SchemeRegistry registry = new SchemeRegistry(); LOG.LogDebug(Module.PLATFORM, "Certificate Validation Enabled = " + this.Validatecertificates()); if (this.Validatecertificates()) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); /******************************** * USING DEFAULT ANDROID DEVICE SSLSocketFactory * the default factory was throwing errors verifying ssl certificates chains for some specific CA Authorities * (for example, Verisign root ceritificate G5 is not available on android devices <=2.3) * See more details on jira ticket [MOBPLAT-63] ******************************** SSLSocketFactory socketFactory = SSLSocketFactory .getSocketFactory();/*from w w w .j a va 2 s.com*/ socketFactory .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); */ /* /******************************** * USING VALIDATING SSLSocketFactory - Validating certificates per demand * See more details on jira ticket [MOBPLAT-63] ******************************** */ KeyStore trustStore; if (Build.VERSION.SDK_INT >= 14) { trustStore = KeyStore.getInstance("AndroidCAStore"); trustStore.load(null, null); } else { try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); ; String filename = "/system/etc/security/cacerts.bks".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); trustStore.load(is, "changeit".toCharArray()); is.close(); } catch (Exception ex) { try { /* /******************************** * HTC 2.3.5 Access Keystore problem * See more details on jira ticket [MOBPLAT-91] ******************************** */ trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); String filename = "/system/etc/security/cacerts.bks".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); trustStore.load(is, null); is.close(); } catch (Exception e) { trustStore = null; LOG.Log(Module.PLATFORM, "A problem has been detected while accessing the device keystore.", e); } } } socketFactory = ValidatingSSLSocketFactory.GetInstance(trustStore); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); LOG.LogDebug(Module.PLATFORM, "Using ValidatingSSLSocketFactory (custom socket Factory)"); } else { /* * ******************************* * USING CUSTOM SSLSocketFactory - accept all certificates * See more details on jira ticket [MOBPLAT-63] ******************************** */ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); socketFactory = new MySSLSocketFactory(trustStore); LOG.LogDebug(Module.PLATFORM, "Using MySSLSocketFactory (custom socket factory - accepting all certificates)"); } registry.register(new Scheme("https", socketFactory, 443)); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(new DefaultHttpClient().getParams(), registry); httpSSLClient = new DefaultHttpClient(mgr, new DefaultHttpClient().getParams()); // [MOBPLAT-200] : allow gzip, deflate decompression modes httpSSLClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); LOG.LogDebug(Module.PLATFORM, "httpSSLClient stored for next HTTPS access"); }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
/** * Return a http client instance/*from w w w . j av a 2 s . c om*/ * * @param port - server port * @param protocol- service endpoint protocol http/https * @return */ public static HttpClient getHttpClient(int port, String protocol) { SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); String ignoreHostnameVerification = System.getProperty("org.wso2.ignoreHostnameVerification"); if (ignoreHostnameVerification != null && "true".equalsIgnoreCase(ignoreHostnameVerification)) { X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; socketFactory.setHostnameVerifier(hostnameVerifier); } if (APIConstants.HTTPS_PROTOCOL.equals(protocol)) { if (port >= 0) { registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, port, socketFactory)); } else { registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, 443, socketFactory)); } } else if (APIConstants.HTTP_PROTOCOL.equals(protocol)) { if (port >= 0) { registry.register( new Scheme(APIConstants.HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory())); } else { registry.register( new Scheme(APIConstants.HTTP_PROTOCOL, 80, PlainSocketFactory.getSocketFactory())); } } HttpParams params = new BasicHttpParams(); ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(tcm, params); }
From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java
@SuppressWarnings("deprecation") private static HttpClient getHttpClient(File keystore, char[] pwd, ClientConnectionManager ccm, int port, int timeout) throws Exception { SchemeRegistry sr = ccm.getSchemeRegistry(); KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType()); truststore.load(new FileInputStream(keystore), pwd); SSLSocketFactory socketFactory = new SSLSocketFactory(truststore); socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sr.register(new Scheme("https", port, socketFactory)); HttpClient httpClient = new DefaultHttpClient(ccm); httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); return httpClient; }
From source file:org.cloudifysource.restclient.RestClient.java
/** * Returns a HTTP client configured to use SSL. * // ww w . j av a 2 s . c o m * @param url * * @return HTTP client configured to use SSL * @throws org.cloudifysource.restclient.exceptions.RestClientException * Reporting different failures while creating the HTTP client */ private DefaultHttpClient getSSLHttpClient(final URL url) throws RestClientException { try { final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // TODO : support self-signed certs if configured by user upon "connect" trustStore.load(null, null); final SSLSocketFactory sf = new RestSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme(HTTPS, sf, url.getPort())); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (final Exception e) { throw new RestClientException(FAILED_CREATING_CLIENT, "Failed creating http client", ExceptionUtils.getFullStackTrace(e)); } }
From source file:org.jboss.as.test.integration.management.api.web.ConnectorTestCase.java
public static HttpClient wrapClient(HttpClient base) { try {/*from w ww. ja v a2 s . c o m*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java
private static HttpClient getTrustAllHttpClient() { try {//from w w w . j av a 2 s .c om SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] temp = new TrustManager[1]; temp[0] = new CxfClientUtilsOld.TrustAllManager(); sslContext.init(null, temp, null); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager connectionManager = httpClient.getConnectionManager(); SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry(); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); return (new DefaultHttpClient(connectionManager, httpClient.getParams())); } catch (Exception e) { logger.error("Unexpected error", e); return (null); } }
From source file:org.restlet.ext.httpclient.HttpClientHelper.java
/** * Configures the scheme registry. By default, it registers the HTTP and the * HTTPS schemes./* w ww. ja v a2s . c om*/ * * @param schemeRegistry * The scheme registry to configure. */ protected void configure(SchemeRegistry schemeRegistry) { schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // [ifndef android] SSLSocketFactory sslSocketFactory = null; SslContextFactory sslContextFactory = SslUtils.getSslContextFactory(this); if (sslContextFactory != null) { try { SSLContext sslContext = sslContextFactory.createSslContext(); sslSocketFactory = new SSLSocketFactory(sslContext); } catch (Exception e) { throw new RuntimeException("Unable to create SSLContext.", e); } } else { sslSocketFactory = SSLSocketFactory.getSocketFactory(); } if (getHostnameVerifier() != null) { try { X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) Engine .loadClass(getHostnameVerifier()).newInstance(); sslSocketFactory.setHostnameVerifier(hostnameVerifier); } catch (Exception e) { getLogger().log(Level.WARNING, "An error occurred during the instantiation of the hostname verifier.", e); } } schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); // [enddef] }
From source file:org.wso2.carbon.appmgt.keymgt.service.APIKeyMgtSubscriberService.java
/** * Renew the ApplicationAccesstoken, Call Token endpoint and get parameters. * Revoke old token.//from w w w . j av a2s .c o m * * @param tokenType * @param oldAccessToken * @param allowedDomains * @param clientId * @param clientSecret * @param validityTime * @return * @throws Exception */ public String renewAccessToken(String tokenType, String oldAccessToken, String[] allowedDomains, String clientId, String clientSecret, String validityTime) throws Exception { String newAccessToken = null; long validityPeriod = 0; // create a post request to getNewAccessToken for client_credentials // grant type. //String tokenEndpoint = OAuthServerConfiguration.getInstance().getTokenEndPoint(); String tokenEndpointName = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_TOKEN_ENDPOINT_NAME); String keyMgtServerURL = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_URL); URL keymgtURL = new URL(keyMgtServerURL); int keyMgtPort = keymgtURL.getPort(); String tokenEndpoint = null; if (keyMgtServerURL != null) { String[] tmp = keyMgtServerURL.split("services"); tokenEndpoint = tmp[0] + tokenEndpointName; } String revokeEndpoint = tokenEndpoint.replace("token", "revoke"); // Below code is to overcome host name verification failure we get in certificate // validation due to self-signed certificate. X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; DefaultHttpClient client = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier(hostnameVerifier); if (keyMgtPort >= 0) { registry.register(new Scheme("https", keyMgtPort, socketFactory)); } else { registry.register(new Scheme("https", 443, socketFactory)); } SingleClientConnManager mgr1 = new SingleClientConnManager(registry); SingleClientConnManager mgr2 = new SingleClientConnManager(registry); HttpClient tokenEPClient = new DefaultHttpClient(mgr1, client.getParams()); HttpClient revokeEPClient = new DefaultHttpClient(mgr2, client.getParams()); HttpPost httpTokpost = new HttpPost(tokenEndpoint); HttpPost httpRevokepost = new HttpPost(revokeEndpoint); // Request parameters. List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3); List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS)); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId)); tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret)); revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId)); revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret)); revokeParams.add(new BasicNameValuePair("token", oldAccessToken)); try { //Revoke the Old Access Token httpRevokepost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8")); HttpResponse revokeResponse = tokenEPClient.execute(httpRevokepost); if (revokeResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + revokeResponse.getStatusLine().getStatusCode()); } else { if (log.isDebugEnabled()) { log.debug("Successfully revoked old application access token"); } } //Generate New Access Token httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8")); HttpResponse tokResponse = revokeEPClient.execute(httpTokpost); HttpEntity tokEntity = tokResponse.getEntity(); if (tokResponse.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + tokResponse.getStatusLine().getStatusCode()); } else { String responseStr = EntityUtils.toString(tokEntity); JSONObject obj = new JSONObject(responseStr); newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString(); validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString()); if (validityTime != null && !"".equals(validityTime)) { validityPeriod = Long.parseLong(validityTime); } } } catch (Exception e2) { String errMsg = "Error in getting new accessToken"; log.error(errMsg); throw new APIKeyMgtException(errMsg, e2); } AppMDAO appMDAO = new AppMDAO(); appMDAO.updateRefreshedApplicationAccessToken(tokenType, newAccessToken, validityPeriod); return newAccessToken; }
From source file:org.wso2.mdm.agent.proxy.utils.ServerUtilities.java
public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException { HttpClient client = null;//from w w w. j a v a 2 s. c o m InputStream inStream = null; try { if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) { KeyStore localTrustStore = KeyStore.getInstance("BKS"); inStream = IdentityProxy.getInstance().getContext().getResources() .openRawResource(R.raw.emm_truststore); localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(connectionManager, params); } else { client = new DefaultHttpClient(); } } catch (KeyStoreException e) { throw new IDPTokenManagerException("Invalid keystore.", e); } catch (CertificateException e) { throw new IDPTokenManagerException("Invalid certificate.", e); } catch (NoSuchAlgorithmException e) { throw new IDPTokenManagerException("Keystore algorithm does not match.", e); } catch (UnrecoverableKeyException e) { throw new IDPTokenManagerException("Invalid keystore.", e); } catch (KeyManagementException e) { throw new IDPTokenManagerException("Invalid keystore.", e); } catch (IOException e) { throw new IDPTokenManagerException("Trust store failed to load.", e); } finally { StreamHandlerUtil.closeInputStream(inStream, TAG); } return client; }