List of usage examples for org.apache.http.client.config AuthSchemes BASIC
String BASIC
To view the source code for org.apache.http.client.config AuthSchemes BASIC.
Click Source Link
From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java
public HttpAbstract(String userAgent, boolean bFollowRedirect, ProxyHandler proxyHandler) { HttpClientBuilder builder = HttpClients.custom(); redirectStrategy = new DefaultRedirectStrategy(); if (userAgent != null) { userAgent = userAgent.trim();//from ww w .ja v a 2 s . co m if (userAgent.length() > 0) builder.setUserAgent(userAgent); else userAgent = null; } if (!bFollowRedirect) builder.disableRedirectHandling(); this.proxyHandler = proxyHandler; Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); credentialsProvider = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(credentialsProvider); cookieStore = new BasicCookieStore(); builder.setDefaultCookieStore(cookieStore); builder.setDefaultCredentialsProvider(credentialsProvider); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); httpClient = builder.build(); }
From source file:org.exoplatform.outlook.mail.MailAPI.java
/** * Instantiates a new mail API.//from w w w. j av a2 s. c om * * @param httpClient the http client * @throws MailServerException the mail server exception */ MailAPI(CloseableHttpClient httpClient) throws MailServerException { if (httpClient == null) { // FYI it's possible make more advanced conn manager settings (host verification X509, conn config, // message parser etc.) PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); // 2 recommended by RFC 2616 sec 8.1.4, we make it bigger for quicker // upload connectionManager.setDefaultMaxPerRoute(10); connectionManager.setMaxTotal(100); // Create global request configuration RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true) .setStaleConnectionCheckEnabled(true).setAuthenticationEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) // .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) // .setCookieSpec(CookieSpecs.BEST_MATCH) .build(); // Create HTTP client this.httpClient = HttpClients.custom().setConnectionManager(connectionManager) // .setDefaultCredentialsProvider(credsProvider) .setDefaultRequestConfig(defaultRequestConfig).build(); } else { // Use given HTTP client (for tests) this.httpClient = httpClient; } // Default header (Accept JSON), add to those requests where required this.acceptJsonHeader = new BasicHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()); // Add AuthCache to the execution context this.httpContext = HttpClientContext.create(); }
From source file:com.wudaosoft.net.httpclient.HostConfigBuilder.java
public HostConfig build() { requestConfig = RequestConfig.custom().setExpectContinueEnabled(false) // .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout).build(); SimpleHostConfig hostCofing = new SimpleHostConfig(requestConfig); hostCofing.setCA(ca);// ww w . j av a 2s .c o m hostCofing.setCaPassword(caPassword); hostCofing.setCharset(charset); hostCofing.setHost(httpHost); hostCofing.setHostUrl(hostUrl); hostCofing.setHostCount(hostCount); hostCofing.setIsMulticlient(multiclient); hostCofing.setPoolSize(poolSize); hostCofing.setReferer(referer); hostCofing.setUserAgent(userAgent); return hostCofing; }
From source file:microsoft.exchange.webservices.data.core.request.HttpClientWebRequest.java
/** * Prepares the request by setting appropriate headers, authentication, timeouts, etc. *///from w w w . ja v a 2s . c o m @Override public void prepareConnection() { httpPost = new HttpPost(getUrl().toString()); // Populate headers. httpPost.addHeader("Content-type", getContentType()); httpPost.addHeader("User-Agent", getUserAgent()); httpPost.addHeader("Accept", getAccept()); httpPost.addHeader("Keep-Alive", "300"); httpPost.addHeader("Connection", "Keep-Alive"); if (isAcceptGzipEncoding()) { httpPost.addHeader("Accept-Encoding", "gzip,deflate"); } if (getHeaders() != null) { for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) { httpPost.addHeader(httpHeader.getKey(), httpHeader.getValue()); } } // Build request configuration. // Disable Kerberos in the preferred auth schemes - EWS should usually allow NTLM or Basic auth RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true) .setConnectionRequestTimeout(getTimeout()).setConnectTimeout(getTimeout()) .setRedirectsEnabled(isAllowAutoRedirect()).setSocketTimeout(getTimeout()) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.BASIC)); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Add proxy credential if necessary. WebProxy proxy = getProxy(); if (proxy != null) { HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort()); requestConfigBuilder.setProxy(proxyHost); if (proxy.hasCredentials()) { NTCredentials proxyCredentials = new NTCredentials(proxy.getCredentials().getUsername(), proxy.getCredentials().getPassword(), "", proxy.getCredentials().getDomain()); credentialsProvider.setCredentials(new AuthScope(proxyHost), proxyCredentials); } } // Add web service credential if necessary. if (isAllowAuthentication() && getUsername() != null) { NTCredentials webServiceCredentials = new NTCredentials(getUsername(), getPassword(), "", getDomain()); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY), webServiceCredentials); } httpContext.setCredentialsProvider(credentialsProvider); httpPost.setConfig(requestConfigBuilder.build()); }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.RemoteStorageContextCustomizer.java
@VisibleForTesting public void applyAuthenticationConfig(final Builder builder, final RemoteAuthenticationSettings ras, final HttpHost proxyHost) { if (ras != null) { String authScope = "target"; if (proxyHost != null) { authScope = proxyHost.toHostString() + " proxy"; }/*from w w w . ja v a 2 s. c o m*/ final List<String> authorisationPreference = Lists.newArrayListWithExpectedSize(3); authorisationPreference.add(AuthSchemes.DIGEST); authorisationPreference.add(AuthSchemes.BASIC); Credentials credentials = null; if (ras instanceof ClientSSLRemoteAuthenticationSettings) { throw new IllegalArgumentException("SSL client authentication not yet supported!"); } else if (ras instanceof NtlmRemoteAuthenticationSettings) { final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authorisationPreference.add(0, AuthSchemes.NTLM); log.debug("{} authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain()); credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()); } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { final UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; log.debug("{} authentication setup for remote storage with username '{}'", authScope, uras.getUsername()); credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()); } if (credentials != null) { if (proxyHost != null) { builder.setCredentials(new AuthScope(proxyHost), credentials); builder.getRequestConfigBuilder().setProxyPreferredAuthSchemes(authorisationPreference); } else { builder.setCredentials(AuthScope.ANY, credentials); builder.getRequestConfigBuilder().setTargetPreferredAuthSchemes(authorisationPreference); } } } }
From source file:org.alfresco.cacheserver.http.CacheHttpClient.java
private CloseableHttpClient getHttpClient(HttpHost target, HttpClientContext localContext, String username, String password) {//from w w w. j a v a 2 s. c o m ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) { // Keep alive for 5 seconds only return 5 * 1000; } else { // otherwise keep alive for 30 seconds return 30 * 1000; } } }; HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setExpectContinueEnabled(true) // .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig) .setDefaultCredentialsProvider(credsProvider).setKeepAliveStrategy(keepAliveStrategy) .setRetryHandler(retryHandler).build(); return httpclient; }
From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java
public AbstractRestClient(URL httpUrl) { super(httpUrl); HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/*from w w w. ja v a2s .c o m*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); CookieStore cookieStore = new BasicCookieStore(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000) .setConnectTimeout(3000).setSocketTimeout(3000).build(); client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider) // .setProxy(new HttpHost("myproxy", 8080)) .setDefaultRequestConfig(defaultRequestConfig).build(); }