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.cncounter.test.httpclient.ClientConfiguration.java
public final static void main(String[] args) throws Exception { // Use custom message parser / writer to customize the way HTTP // messages are parsed from and written out to the data stream. HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override// w w w . j av a 2 s.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(); // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); // Client HTTP connection objects when fully initialized can be bound to // an arbitrary network socket. The process of network socket initialization, // its connection to a remote address and binding to a local one is controlled // by a connection socket factory. // SSL context for secure connections can be created either based on // system or application specific properties. SSLContext sslcontext = SSLContexts.createSystemDefault(); // Use custom hostname verifier to customize SSL hostname verification. X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); // Create message constraints MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore cookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Create global request configuration RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager) .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider) .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build(); try { HttpGet httpget = new HttpGet("http://www.apache.org/"); // Request configuration can be overridden at the request level. // They will take precedence over the one set at the client level. RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000) .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setProxy(new HttpHost("myotherproxy", 8080)).build(); httpget.setConfig(requestConfig); // Execution context can be customized locally. HttpClientContext context = HttpClientContext.create(); // Contextual attributes set the local context level will take // precedence over those set at the client level. context.setCookieStore(cookieStore); context.setCredentialsProvider(credentialsProvider); System.out.println("executing request " + httpget.getURI()); CloseableHttpResponse response = httpclient.execute(httpget, context); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); // Once the request has been executed the local context can // be used to examine updated state and various objects affected // by the request execution. // Last executed request context.getRequest(); // Execution route context.getHttpRoute(); // Target auth state context.getTargetAuthState(); // Proxy auth state context.getTargetAuthState(); // Cookie origin context.getCookieOrigin(); // Cookie spec used context.getCookieSpec(); // User security token context.getUserToken(); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.datatorrent.stram.util.WebServicesClientTest.java
public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException, IllegalAccessException { CredentialsProvider provider = getCredentialsProvider(); String httpScheme = AuthScope.ANY_SCHEME; if (authScheme == AuthScheme.BASIC) { httpScheme = AuthSchemes.BASIC; } else if (authScheme == AuthScheme.DIGEST) { httpScheme = AuthSchemes.DIGEST; }//from w w w .j a va 2 s . co m AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme); Credentials credentials = provider.getCredentials(authScope); Assert.assertNotNull("Credentials", credentials); Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass())); UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials) credentials; Assert.assertEquals("Username", username, pwdCredentials.getUserName()); Assert.assertEquals("Password", password, pwdCredentials.getPassword()); }
From source file:io.cloudslang.content.httpclient.build.auth.AuthSchemeProviderLookupBuilderTest.java
@Test public void buildLookupWithBasicAuth() { AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.BASIC); assertThat(provider, instanceOf(BasicSchemeFactory.class)); BasicScheme basicSchema = ((BasicScheme) provider.create(null)); assertEquals("UTF-8", basicSchema.getCredentialsCharset().toString()); }
From source file:com.wudaosoft.net.httpclient.DefaultHostConfig.java
public DefaultHostConfig() { defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(false) // .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(500) .setConnectTimeout(10000).setSocketTimeout(10000).build(); }
From source file:com.kms.core.io.HttpUtil_In.java
public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) { CloseableHttpClient httpclient;/* w ww . j a v a 2s .co m*/ // Auth Scheme final 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(); // NTLM final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080), new NTCredentials(SoeID, Password, "dummy", "APAC")); //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" )); // ------------- cookie start ------------------------ // Auction // Create a local instance of cookie store final CookieStore cookieStore = new BasicCookieStore(); // Cookie . final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES"); cookie.setVersion(0); cookie.setDomain(".scourt.go.kr"); cookie.setPath("/"); cookieStore.addCookie(cookie); // ------------- cookie end ------------------------ if (type == 0) // TYPE.AuctionInput { // HTTP Client httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credsProvider).build(); } else // SagunInput { // HTTP Client httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build(); } return httpclient; }
From source file:com.ibm.watson.app.common.util.http.HttpClientBuilder.java
public static CloseableHttpClient buildDefaultHttpClient(Credentials cred) { // Use custom cookie store if necessary. CookieStore cookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); RequestConfig defaultRequestConfig;//ww w. j a v a2 s . c o m //private DefaultHttpClient client; connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(50); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(builder.build())).build(); } catch (Exception e) { logger.warn(MessageKey.AQWEGA02000W_unable_init_ssl_context.getMessage(), e); } // Create global request configuration defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true) .setTargetPreferredAuthSchemes( Arrays.asList(AuthSchemes.BASIC, AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setAuthenticationEnabled(true).build(); if (cred != null) credentialsProvider.setCredentials(AuthScope.ANY, cred); return HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig) .build(); }
From source file:com.datatorrent.stram.util.WebServicesClient.java
public static void initAuth(ConfigProvider configuration) { // Setting up BASIC and DIGEST auth setupUserPassAuthScheme(AuthScheme.BASIC, AuthSchemes.BASIC, new BasicSchemeFactory(), configuration); setupUserPassAuthScheme(AuthScheme.DIGEST, AuthSchemes.DIGEST, new DigestSchemeFactory(), configuration); // Adding kerberos standard auth setupHttpAuthScheme(AuthSchemes.KERBEROS, new KerberosSchemeFactory(), AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS);//w w w . j av a2 s . c o m authRegistry = registryBuilder.build(); }
From source file:org.openscore.content.httpclient.build.auth.AuthSchemeProviderLookupBuilder.java
public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() { RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); for (String type : authTypes) { switch (type.trim()) { case "NTLM": registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() { @Override//from w w w. j av a 2 s .c om public AuthScheme create(HttpContext httpContext) { return new NTLMScheme(new JCIFSEngine()); } }); break; case "BASIC": registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName("UTF-8"))); String value = username + ":" + password; byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)); headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue))); break; case "DIGEST": registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; case "KERBEROS": if (getSettingsKey().equals(System.getProperty("oohttpclient.krb.last.settings"))) { break; } if (kerberosConfigFile != null) { System.setProperty("java.security.krb5.conf", kerberosConfigFile); } else { File krb5Config; String domain = host.replaceAll(".*\\.(?=.*\\.)", ""); try { krb5Config = createKrb5Configuration(domain); } catch (IOException e) { throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e); } System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); } if (kerberosLoginConfigFile != null) { System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile); } else { File loginConfig; try { loginConfig = createLoginConfig(); } catch (IOException e) { throw new RuntimeException( "could not create the kerberos login config file" + e.getMessage(), e); } System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); } //todo fix security issue if (password != null) { System.setProperty(KrbHttpLoginModule.PAS, password); } if (username != null) { System.setProperty(KrbHttpLoginModule.USR, username); } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup); registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort)); registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort)); System.setProperty("oohttpclient.krb.last.settings", getSettingsKey()); break; default: throw new IllegalStateException( "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type); } } return registryBuilder.build(); }
From source file:io.cloudslang.content.httpclient.build.auth.AuthSchemeProviderLookupBuilder.java
public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() { RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); for (String type : authTypes) { switch (type.trim()) { case "NTLM": registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() { @Override/*from ww w. java 2s. c om*/ public AuthScheme create(HttpContext httpContext) { return new NTLMScheme(new JCIFSEngine()); } }); break; case "BASIC": registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName(Utils.DEFAULT_CHARACTER_SET))); String value = username + ":" + password; byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)); headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue))); break; case "DIGEST": registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; case "KERBEROS": if (kerberosConfigFile != null) { System.setProperty("java.security.krb5.conf", kerberosConfigFile); } else { File krb5Config; String domain = host.replaceAll(".*\\.(?=.*\\.)", ""); try { krb5Config = createKrb5Configuration(domain); } catch (IOException e) { throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e); } System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); } if (kerberosLoginConfigFile != null) { System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile); } else { File loginConfig; try { loginConfig = createLoginConfig(); } catch (IOException e) { throw new RuntimeException( "could not create the kerberos login config file" + e.getMessage(), e); } System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); } if (password != null) { System.setProperty(KrbHttpLoginModule.PAS, password); } if (username != null) { System.setProperty(KrbHttpLoginModule.USR, username); } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup); registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort)); registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort)); break; case AuthTypes.ANONYMOUS: break; default: throw new IllegalStateException( "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type); } } return registryBuilder.build(); }
From source file:com.apm4all.tracy.TracyAsyncHttpClientPublisher.java
@Override public boolean publish(String tracySegment) { boolean published = true; HttpPost httpPost;//from w w w.j av a2s . c om if (null != this.uri) { if (httpProxyConfig.isEnabled()) { HttpHost proxy = new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort(), "http"); RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).setAuthenticationEnabled(true) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); httpPost = new HttpPost(uri); httpPost.setConfig(reqConfig); } else { httpPost = new HttpPost(uri); } StringEntity se; try { se = new StringEntity(tracySegment, StandardCharsets.UTF_8); se.setContentType(MediaType.APPLICATION_JSON); httpPost.setEntity(se); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, TRACY_CONTENT_TYPE); Future<HttpResponse> future = httpClient.execute(httpPost, null); if (waitForResponse) { HttpResponse response = future.get(); published = (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK); if (debug) { System.out.println(extractPostResponse(response)); } } } catch (Exception e) { } } return published; }