List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java
public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) { DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager()); SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry(); schemeRegistry.unregister("https"); try {//from ww w . j a v a 2 s .c o m SSLContext instance = SSLContext.getInstance("TLS"); TrustManager tm = UnsecureX509TrustManager.INSTANCE; instance.init(null, new TrustManager[] { tm }, null); schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))); } catch (Exception e) { throw new RuntimeException("TLS issue", e); } httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class); httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies()); HttpParams params = httpclient.getParams(); if (proxy != null) { ConnRouteParams.setDefaultProxy(params, proxy); } HttpConnectionParams.setSoTimeout(params, 7000); return httpclient; }
From source file:net.bither.image.http.BaseHttpResponse.java
private DefaultHttpClient getThreadSafeHttpClient() { DefaultHttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager mgr = httpClient.getConnectionManager(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HttpSetting.HTTP_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HttpSetting.HTTP_SO_TIMEOUT); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);//from ww w . ja v a 2 s . c o m return httpClient; }
From source file:org.envirocar.wps.TrackToCSVProcess.java
protected HttpClient createClient() throws IOException { SSLSocketFactory sslsf;//from www . j a v a2 s. c o m try { sslsf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { // XXX !!! return true; } }, new StrictHostnameVerifier()); } catch (KeyManagementException e) { throw new IOException(e); } catch (UnrecoverableKeyException e) { throw new IOException(e); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (KeyStoreException e) { throw new IOException(e); } Scheme httpsScheme2 = new Scheme("https", 443, sslsf); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme2); return client; }
From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
@NonNull private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url, @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException { UserCredentials result = null;//from w w w . ja v a2 s. c o m String realm = null; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs); // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(params); // create local execution context HttpContext localContext = new BasicHttpContext(); final HttpGet httpGet = new HttpGet(url); if (inHeaders != null) { for (Header header : inHeaders) { httpGet.addHeader(header); } } // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); if (DEBUG) { try { URI uri = new URI(url); ProxySelector sel = routePlanner.getProxySelector(); if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$ List<Proxy> list = sel.select(uri); System.out.printf("SdkLib.UrlOpener:\n Connect to: %s\n Proxy List: %s\n", //$NON-NLS-1$ url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$ } } catch (Exception e) { System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$ url, e.toString()); } } boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpGet, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (DEBUG) { System.out.printf(" Status: %d\n", statusCode); //$NON-NLS-1$ } // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. InputStream is = new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { // Since Http Client is no longer needed, close it. // Bug #21167: we need to tell http client to shutdown // first, otherwise the super.close() would continue // downloading and not return till complete. httpClient.getConnectionManager().shutdown(); super.close(); } }; HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(is, outResponse); } } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // It's ok to not have an entity (e.g. nothing to download) for a 304 HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(null, outResponse); } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:org.github.oauth2.AccessTokenClient.java
/** * Execute request and return response//from w w w . j a va2 s.co m * * @param target * @param request * @return response * @throws IOException */ protected HttpResponse execute(HttpHost target, HttpRequest request) throws IOException { DefaultHttpClient client = new DefaultHttpClient(); client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); return client.execute(target, request); }
From source file:org.envirocar.harvest.TrackPublisher.java
protected HttpClient createClient() throws IOException { SSLSocketFactory sslsf;/*from w w w .ja v a 2s . c om*/ try { sslsf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { // XXX !!! return true; } }, new LoggingHostnameVerifier()); } catch (KeyManagementException e) { throw new IOException(e); } catch (UnrecoverableKeyException e) { throw new IOException(e); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (KeyStoreException e) { throw new IOException(e); } Scheme httpsScheme2 = new Scheme("https", 443, sslsf); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme2); return client; }
From source file:info.smartkit.hairy_batman.demo.MoniterWechatBrowser.java
/** * ?URLhtml?// ww w . ja va 2 s. c om */ @SuppressWarnings("deprecation") public static String getHttpClientHtml(String url, String code, String userAgent) { String html = null; @SuppressWarnings("deprecation") DefaultHttpClient httpClient = new DefaultHttpClient();// httpClient HttpGet httpget = new HttpGet(url);// get?URL // Pause for 4 seconds try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); System.out.println(e1.toString()); } // httpget.setHeader("User-Agent", userAgent); try { // responce HttpResponse responce = httpClient.execute(httpget); // ? int returnCode = responce.getStatusLine().getStatusCode(); // 200? ? if (returnCode == HttpStatus.SC_OK) { // HttpEntity entity = responce.getEntity(); if (entity != null) { html = new String(EntityUtils.toString(entity));// html?? } } } catch (Exception e) { System.out.println(""); e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return html; }
From source file:org.eclipse.thym.core.engine.internal.cordova.NpmBasedEngineRepoProvider.java
private InputStream getRemoteJSonStream(String url) throws IOException { try {/*from ww w. j av a 2s .c om*/ // SSLSocketFactory to patch HTTPClient's that are earlier than 4.3.2 // to enable SNI support. SSLSocketFactory factory = new SSLSocketFactory(SSLContext.getDefault()) { @Override public Socket createSocket() throws IOException { return SocketFactory.getDefault().createSocket(); } @Override public Socket createSocket(HttpParams params) throws IOException { return SocketFactory.getDefault().createSocket(); } }; DefaultHttpClient client = new DefaultHttpClient(); HttpUtil.setupProxy(client); client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, factory)); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); return entity.getContent(); } catch (NoSuchAlgorithmException e) { HybridCore.log(IStatus.ERROR, "Error creating the SSL Factory ", e); } return null; }
From source file:org.wso2.carbon.identity.thrift.authentication.client.internal.pool.SecureClientPoolFactory.java
@Override public AuthenticatorService.Client makeObject(Object key) throws ThriftAuthenticationException, TTransportException { String[] keyElements = constructKeyElements((String) key); if (keyElements[0].equals(ThriftAuthenticationClient.Protocol.SSL.toString())) { if (params == null) { if (trustStore == null) { trustStore = System.getProperty("javax.net.ssl.trustStore"); if (trustStore == null) { throw new ThriftAuthenticationException("No trustStore found"); }/*from w w w . ja va2 s. c o m*/ } if (trustStorePassword == null) { trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePassword == null) { throw new ThriftAuthenticationException("No trustStore password found"); } //trustStorePassword = "wso2carbon"; } params = new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(trustStore, trustStorePassword); } TTransport receiverTransport = TSSLTransportFactory.getClientSocket(keyElements[1], Integer.parseInt(keyElements[2]), 0, params); TProtocol protocol = new TBinaryProtocol(receiverTransport); return new AuthenticatorService.Client(protocol); } else { try { TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; // String[] hostNameAndPort = keyElements[3].split(ThriftAuthenticationClientConstants.HOSTNAME_AND_PORT_SEPARATOR); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(keyElements[2])); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme); THttpClient tclient = new THttpClient( "https://" + keyElements[1] + ":" + keyElements[2] + "/thriftAuthenticator", client); TProtocol protocol = new TCompactProtocol(tclient); AuthenticatorService.Client authClient = new AuthenticatorService.Client(protocol); tclient.open(); return authClient; } catch (Exception e) { throw new ThriftAuthenticationException( "Cannot create Secure client for " + keyElements[1] + ":" + keyElements[2], e); } } }
From source file:org.globus.crux.security.ClientTest.java
/** * Test client with invalid credentials. * /*from ww w . j a v a 2 s.c o m*/ * @throws Exception * This should happen. */ @Test public void testInvalid() throws Exception { SSLConfigurator config = getConfig("classpath:/invalidkeystore.properties"); SSLSocketFactory fac = new SSLSocketFactory(config.getSSLContext()); fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); Scheme scheme = new Scheme("https", fac, getPort()); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); try { httpclient.execute(httpget); fail(); } catch (SSLPeerUnverifiedException ex) { // this better happen } }