List of usage examples for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier
public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier)
From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java
HttpClient http() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { if (client == null) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout()); HttpConnectionParams.setSoTimeout(params, getSoTimeout()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);//from w w w . j a v a2s. co m SSLSocketFactory sf = new EasySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); /* * ClientConnectionManager mgr = new ThreadSafeClientConnManager( * params, registry); */ ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(mgr, params); // gzip? defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); client = defaultHttpClient; } return client; }
From source file:com.enjoy.nerd.http.AsyncHttpClient.java
/** * Returns default instance of SchemeRegistry * * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification * @param httpPort HTTP port to be used, must be greater than 0 * @param httpsPort HTTPS port to be used, must be greater than 0 *//*from www. j a va 2 s . c o m*/ private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) { if (fixNoHttpResponseException) { Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates."); } if (httpPort < 1) { httpPort = 80; Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80"); } if (httpsPort < 1) { httpsPort = 443; Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443"); } // Fix to SSL flaw in API < ICS // See https://code.google.com/p/android/issues/detail?id=13117 SSLSocketFactory sslSocketFactory; if (fixNoHttpResponseException) sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory(); else sslSocketFactory = SSLSocketFactory.getSocketFactory(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort)); if (sslSocketFactory != null) { sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort)); } return schemeRegistry; }
From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java
private Socket constructSSLSocket(Context context, String host, int port) throws SignalingException { try {//from ww w.java 2 s .co m AssetManager assetManager = context.getAssets(); InputStream keyStoreInputStream = assetManager.open("whisper.store"); KeyStore trustStore = KeyStore.getInstance("BKS"); trustStore.load(keyStoreInputStream, "whisper".toCharArray()); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore); if (Release.SSL) { sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } else { Log.w("SignalingSocket", "Disabling hostname verification..."); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } return timeoutHackConnect(sslSocketFactory, host, port); } catch (IOException ioe) { throw new SignalingException(ioe); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (KeyStoreException e) { throw new IllegalArgumentException(e); } catch (CertificateException e) { throw new IllegalArgumentException(e); } catch (KeyManagementException e) { throw new IllegalArgumentException(e); } catch (UnrecoverableKeyException e) { throw new IllegalArgumentException(e); } }
From source file:com.betfair.cougar.client.HttpClientExecutable.java
public void init() throws Exception { super.init(); // create client if not been set externally (e.g for testing) if (client == null) { client = new DefaultHttpClient(clientConnectionManager); ((DefaultHttpClient) client).setUserTokenHandler(userTokenHandler); }// ww w. j a v a 2 s . co m // configure retryhandler if set if (retryHandler != null) { ((AbstractHttpClient) client).setHttpRequestRetryHandler(retryHandler); } // configure timeout if set if (connectTimeout != -1) { HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, connectTimeout); HttpConnectionParams.setSoTimeout(params, connectTimeout); } //Configure SSL - if relevant if (transportSSLEnabled) { KeyStoreManagement keyStore = KeyStoreManagement.getKeyStoreManagement(httpsKeystoreType, httpsKeystore, httpsKeyPassword); if (jmxControl != null && keyStore != null) { jmxControl.registerMBean("CoUGAR:name=HttpClientKeyStore,beanName=" + beanName, keyStore); } KeyStoreManagement trustStore = KeyStoreManagement.getKeyStoreManagement(httpsTruststoreType, httpsTruststore, httpsTrustPassword); if (jmxControl != null) { jmxControl.registerMBean("CoUGAR:name=HttpClientTrustStore,beanName=" + beanName, trustStore); } SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore != null ? keyStore.getKeyStore() : null, keyStore != null ? httpsKeyPassword : null, trustStore.getKeyStore()); if (hostnameVerificationDisabled) { socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); LOGGER.warn("CRITICAL SECURITY CHECKS ARE DISABLED: server SSL certificate hostname " + "verification is turned off."); } Scheme sch = new Scheme("https", extractPortFromAddress(), socketFactory); client.getConnectionManager().getSchemeRegistry().register(sch); } metrics = new HttpClientTransportMetrics(); if (jmxControl != null) { jmxControl.registerMBean("CoUGAR:name=HttpClientExecutable,beanName=" + beanName, this); } }
From source file:com.yahala.ui.LoginActivitySmsView.java
public void sendSmsRequest() { Utilities.globalQueue.postRunnable(new Runnable() { @Override//from ww w.j av a2 s .c o m public void run() { try { HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8); httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); SchemeRegistry registry = new SchemeRegistry(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry); HttpClient httpClient = new DefaultHttpClient(manager, httpParams); // HttpGet httpget = new HttpGet("/nhttps://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"+ phoneHash); HttpGet httpget = new HttpGet( "https://rest.nexmo.com/sms/json?api_key=***********&api_secret=***********=NEXMO&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); if (!Utils.IsInDebugMode()) { HttpResponse response = httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { FileLog.e("yahala", "Sms sent" + response.getEntity().getContent()); } else { FileLog.e("/nyahala", "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); } } else { Toast.makeText(getContext(), phoneHash, Toast.LENGTH_LONG); FileLog.e("/nyahala", "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); } } catch (Exception e) { FileLog.e("yahala", e); } } }); }
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException { HttpClient base = new DefaultHttpClient(); SSLContext ctx = null;// w ww . j a v a 2s. c o m try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException ex) { log("exception in sendFormPost():"); } X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; try { ctx.init(null, new TrustManager[] { tm }, null); } catch (KeyManagementException ex) { log("exception in sendFormPost():"); } 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)); HttpClient client = new DefaultHttpClient(ccm, base.getParams()); try { HttpPost post = new HttpPost(url); MultipartEntity multipart = new MultipartEntity(); for (String key : additionalParams.keySet()) multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8"))); if (proj != null) { multipart.addPart("uploaded_file", new FileBody(proj)); } post.setEntity(multipart); HttpResponse resp = client.execute(post); HttpEntity out = resp.getEntity(); InputStream in = out.getContent(); return FileUtils.readStream(in); } catch (Exception ex) { throw new IOException("POST failed", ex); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception ex) { // ignore } } }
From source file:com.sogeti.droidnetworking.NetworkEngine.java
public void init(final Context context, final Map<String, String> headers) { this.context = context; // Setup a queue for operations sharedNetworkQueue = Executors.newFixedThreadPool(2); // Init the memory cache, if the default memory cache size shouldn't be used, set the // size using setMemoryCacheSize before calling init if (memoryCacheSize > 0) { memoryCache = new LruCache<String, CacheEntry>(memoryCacheSize) { protected int sizeOf(final String key, final CacheEntry entry) { return entry.size(); }//from w w w . j a v a 2 s .c om }; } else { memoryCache = null; } // Init the disk cache, if the default disk cache size shouldn't be used, set the // size using setDiskCacheSize before calling init if (diskCacheSize > 0) { try { diskCache = DiskLruCache.open(context.getCacheDir(), DISK_CACHE_VERSION, DISK_CACHE_VALUE_COUNT, diskCacheSize); } catch (IOException e) { diskCache = null; } } else { diskCache = null; } // Setup HTTP SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort)); // Setup HTTPS (accept all certificates) HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); schemeRegistry.register(new Scheme("https", socketFactory, httpsPort)); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(connManager, params); if (headers == null) { this.headers = new HashMap<String, String>(); } else { this.headers = headers; } if (!this.headers.containsKey("User-Agent")) { try { PackageInfo packageInfo = this.context.getPackageManager() .getPackageInfo(this.context.getPackageName(), 0); this.headers.put("User-Agent", packageInfo.packageName + "/" + packageInfo.versionName); } catch (NameNotFoundException e) { this.headers.put("User-Agent", "Unknown/0.0"); } } }
From source file:fr.univsavoie.ltp.client.map.Session.java
/** * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS). * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...) *///from w w w. j av a 2s . c om private void secureAuth() { try { // Instance de SharedPreferences pour lire les donnes dans un fichier SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE); String login = myPrefs.getString("Login", null); String password = myPrefs.getString("Password", null); HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Enable HTTP parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object. SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sslFactory, 443)); // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(ccm, params); CredentialsProvider authCred = new BasicCredentialsProvider(); Credentials creds = new UsernamePasswordCredentials(login, password); authCred.setCredentials(AuthScope.ANY, creds); httpClient.addRequestInterceptor(preemptiveAuth, 0); httpClient.setCredentialsProvider(authCred); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } }
From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java
/** * Returns default instance of SchemeRegistry * * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification * @param httpPort HTTP port to be used, must be greater than 0 * @param httpsPort HTTPS port to be used, must be greater than 0 *///from w ww .j a va 2 s. com private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort, int httpsPort) { if (fixNoHttpResponseException) { YmLog.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates."); } if (httpPort < 1) { httpPort = 80; YmLog.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80"); } if (httpsPort < 1) { httpsPort = 443; YmLog.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443"); } // Fix to SSL flaw in API < ICS // See https://code.google.com/p/android/issues/detail?id=13117 SSLSocketFactory sslSocketFactory; if (fixNoHttpResponseException) { sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory(); } else { sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort)); schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort)); return schemeRegistry; }