List of usage examples for org.apache.http.client.params HttpClientParams setAuthenticating
public static void setAuthenticating(final HttpParams params, final boolean value)
From source file:net.adamcin.httpsig.http.apache4.Http4Util.java
public static void enableAuth(final AbstractHttpClient client, final Keychain keychain, final KeyId keyId) { if (client == null) { throw new NullPointerException("client"); }/*from w w w.j ava 2s . com*/ if (keychain == null) { throw new NullPointerException("keychain"); } client.getAuthSchemes().register(Constants.SCHEME, new AuthSchemeFactory() { public AuthScheme newInstance(HttpParams params) { return new Http4SignatureAuthScheme(); } }); Signer signer = new Signer(keychain, keyId); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new SignerCredentials(signer)); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(Constants.SCHEME)); HttpClientParams.setAuthenticating(client.getParams(), true); }
From source file:com.google.android.apps.authenticator.testability.HttpClientFactory.java
private static void configureHttpClient(HttpClient httpClient) { HttpParams params = httpClient.getParams(); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT_MILLIS); HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setTimeout(params, DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS); // Don't handle redirects automatically HttpClientParams.setRedirecting(params, false); // Don't handle authentication automatically HttpClientParams.setAuthenticating(params, false); }
From source file:cn.keke.travelmix.HttpClientHelper.java
public static HttpClient getNewHttpClient() { try {//from ww w .j a v a2 s . co m SSLSocketFactory sf = new EasySSLSocketFactory(); // TODO test, if SyncBasicHttpParams is needed HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpConnectionParams.setLinger(params, 1); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setSoReuseaddr(params, true); HttpConnectionParams.setTcpNoDelay(params, true); HttpClientParams.setCookiePolicy(params, CookiePolicy.IGNORE_COOKIES); HttpClientParams.setAuthenticating(params, false); HttpClientParams.setRedirecting(params, false); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(registry, 20, TimeUnit.MINUTES); ccm.setMaxTotal(100); ccm.setDefaultMaxPerRoute(20); return new DefaultHttpClient(ccm, params); } catch (Exception e) { LOG.warn("Failed to create custom http client. Default http client is created", e); return new DefaultHttpClient(); } }
From source file:ch.cyberduck.core.http.HTTP4Session.java
/** * Create new HTTP client with default configuration and custom trust manager. * * @return A new instance of a default HTTP client. *//* w ww.ja va 2 s .co m*/ protected AbstractHttpClient http() { if (null == http) { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, getEncoding()); HttpProtocolParams.setUserAgent(params, getUserAgent()); AuthParams.setCredentialCharset(params, "ISO-8859-1"); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoTimeout(params, timeout()); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpClientParams.setRedirecting(params, true); HttpClientParams.setAuthenticating(params, true); SchemeRegistry registry = new SchemeRegistry(); // Always register HTTP for possible use with proxy registry.register(new Scheme("http", host.getPort(), PlainSocketFactory.getSocketFactory())); if ("https".equals(this.getHost().getProtocol().getScheme())) { org.apache.http.conn.ssl.SSLSocketFactory factory = new SSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(), org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme(host.getProtocol().getScheme(), host.getPort(), factory)); } if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if ("https".equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPSProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host))); } } if ("http".equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host))); } } } ClientConnectionManager manager = new SingleClientConnManager(registry); http = new DefaultHttpClient(manager, params); this.configure(http); } return http; }
From source file:com.dahl.brendan.wordsearch.util.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. *///from w w w. j a v a 2 s . c o m public static AndroidHttpClient newInstance(String userAgent) { HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, false); HttpClientParams.setAuthenticating(params, false); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); }
From source file:ch.cyberduck.core.http.HttpSession.java
protected AbstractHttpClient http(final String hostname) { if (!clients.containsKey(hostname)) { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, getEncoding()); HttpProtocolParams.setUserAgent(params, getUserAgent()); AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset")); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoTimeout(params, timeout()); HttpConnectionParams.setConnectionTimeout(params, timeout()); HttpConnectionParams.setSocketBufferSize(params, Preferences.instance().getInteger("http.socket.buffer")); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpClientParams.setRedirecting(params, true); HttpClientParams.setAuthenticating(params, true); HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH); // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager HttpClientParams.setConnectionManagerTimeout(params, Preferences.instance().getLong("http.manager.timeout")); SchemeRegistry registry = new SchemeRegistry(); // Always register HTTP for possible use with proxy registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(), PlainSocketFactory.getSocketFactory())); registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(), new SSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(), new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { log.warn("Hostname verification disabled for:" + host); }/*from w ww . jav a 2s . c o m*/ @Override public void verify(String host, X509Certificate cert) throws SSLException { log.warn("Hostname verification disabled for:" + host); } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { log.warn("Hostname verification disabled for:" + host); } @Override public boolean verify(String s, javax.net.ssl.SSLSession sslSession) { log.warn("Hostname verification disabled for:" + s); return true; } }))); if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.get(); if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPSProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host))); } } if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host))); } } } PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry); manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total")); manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route")); AbstractHttpClient http = new DefaultHttpClient(manager, params); this.configure(http); clients.put(hostname, http); } return clients.get(hostname); }
From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java
protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity, List<NameValuePair> qparams, CallingContext cc) throws IOException { HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); // setup client HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY); HttpClient client = factory.createHttpClient(httpParams); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); // redirect limit is set to some unreasonably high number // resets of the socket cause a retry up to MAX_REDIRECTS times, // so we should be careful not to set this too high... httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // context holds authentication state machine, so it cannot be // shared across independent activities. HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); HttpUriRequest request = null;/*from w w w .jav a 2s. c o m*/ if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new IllegalStateException("No body supplied for POST, PATCH or PUT request"); } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new IllegalStateException("Body was supplied for GET or DELETE request"); } URI nakedUri; try { nakedUri = new URI(url); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e); } if (qparams == null) { qparams = new ArrayList<NameValuePair>(); } URI uri; try { uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null); } catch (URISyntaxException e1) { e1.printStackTrace(); throw new IllegalStateException(e1); } System.out.println(uri.toString()); if (GET.equals(method)) { HttpGet get = new HttpGet(uri); request = get; } else if (DELETE.equals(method)) { HttpDelete delete = new HttpDelete(uri); request = delete; } else if (PATCH.equals(method)) { HttpPatch patch = new HttpPatch(uri); patch.setEntity(entity); request = patch; } else if (POST.equals(method)) { HttpPost post = new HttpPost(uri); post.setEntity(entity); request = post; } else if (PUT.equals(method)) { HttpPut put = new HttpPut(uri); put.setEntity(entity); request = put; } else { throw new IllegalStateException("Unexpected request method"); } HttpResponse resp = client.execute(request); return resp; }
From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java
/** * Creates a new fetcher for fetching HTTP objects. Not really suitable * for production use. Use of an HTTP proxy for security is also necessary * for production deployment.//ww w.j ava 2 s . co m * * @param maxObjSize Maximum size, in bytes, of the object we will fetch, 0 if no limit.. * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts. * @param readTimeoutMs timeout, in millseconds, for unresponsive connections * @param basicHttpFetcherProxy The http proxy to use. */ public BasicHttpFetcher(int maxObjSize, int connectionTimeoutMs, int readTimeoutMs, String basicHttpFetcherProxy) { // Create and initialize HTTP parameters setMaxObjectSizeBytes(maxObjSize); setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING); HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, connectionTimeoutMs); // These are probably overkill for most sites. ConnManagerParams.setMaxTotalConnections(params, 1152); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256)); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, "Apache Shindig"); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, readTimeoutMs); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpClientParams.setRedirecting(params, true); HttpClientParams.setAuthenticating(params, false); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient client = new DefaultHttpClient(cm, params); // Set proxy if set via guice. if (!StringUtils.isEmpty(basicHttpFetcherProxy)) { String[] splits = basicHttpFetcherProxy.split(":"); ConnRouteParams.setDefaultProxy(client.getParams(), new HttpHost(splits[0], Integer.parseInt(splits[1]), "http")); } // try resending the request once client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true)); // Add hooks for gzip/deflate client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final org.apache.http.HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip, deflate"); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final org.apache.http.HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { for (HeaderElement codec : ceheader.getElements()) { String codecname = codec.getName(); if ("gzip".equalsIgnoreCase(codecname)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } else if ("deflate".equals(codecname)) { response.setEntity(new DeflateDecompressingEntity(response.getEntity())); return; } } } } } }); client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler()); // Disable automatic storage and sending of cookies (see SHINDIG-1382) client.removeRequestInterceptorByClass(RequestAddCookies.class); client.removeResponseInterceptorByClass(ResponseProcessCookies.class); // Use Java's built-in proxy logic in case no proxy set via guice. if (StringUtils.isEmpty(basicHttpFetcherProxy)) { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } FETCHER = client; }
From source file:com.mpower.mintel.android.utilities.WebUtils.java
public static final HttpClient createHttpClient(int timeout) { // configure connection HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(params, true); // support authenticating HttpClientParams.setAuthenticating(params, true); // if possible, bias toward digest auth (may not be in 4.0 beta 2) List<String> authPref = new ArrayList<String>(); authPref.add(AuthPolicy.DIGEST);/*from www.j a va2s. c om*/ authPref.add(AuthPolicy.BASIC); // does this work in Google's 4.0 beta 2 snapshot? params.setParameter("http.auth-target.scheme-pref", authPref); // setup client HttpClient httpclient = new DefaultHttpClient(params); httpclient.getParams().setParameter(ClientPNames.MAX_REDIRECTS, 1); httpclient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); return httpclient; }
From source file:org.restlet.ext.httpclient.HttpClientHelper.java
/** * Configures the various parameters of the connection manager and the HTTP * client./*from w ww . j av a2 s . c o m*/ * * @param params * The parameter list to update. */ protected void configure(HttpParams params) { ConnManagerParams.setMaxTotalConnections(params, getMaxTotalConnections()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnectionsPerHost())); // Configure other parameters HttpClientParams.setAuthenticating(params, false); HttpClientParams.setRedirecting(params, isFollowRedirects()); HttpClientParams.setCookiePolicy(params, "ignore"); HttpConnectionParams.setTcpNoDelay(params, getTcpNoDelay()); HttpConnectionParams.setConnectionTimeout(params, getSocketConnectTimeoutMs()); HttpConnectionParams.setSoTimeout(params, getSocketTimeout()); String httpProxyHost = getProxyHost(); if (httpProxyHost != null) { HttpHost proxy = new HttpHost(httpProxyHost, getProxyPort()); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } }