private void delete(String url) throws IOException, HttpException { CredentialsProvider credentials = credentialsProvider(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentials) .build(); try { HttpDelete httpDelete = new HttpDelete(url); httpDelete.setHeader("Accept", "application/json"); System.out.println("Executing request " + httpDelete.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpDelete); try { LOG.debug("----------------------------------------"); LOG.debug((String)response.getStatusLine().getReasonPhrase()); } finally { response.close(); } } finally { httpclient.close(); } }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() != null || authState.hasAuthOptions()) { return; } // If no authState has been established and this is a PUT or POST request, add preemptive authorisation String requestMethod = request.getRequestLine().getMethod(); if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (credentials == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, credentials); } }
@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(serviceUser, servicePass)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
private void configureCredentials(HttpClientBuilder builder, CredentialsProvider credentialsProvider, Collection<Authentication> authentications) { if(authentications.size() > 0) { useCredentials(credentialsProvider, AuthScope.ANY_HOST, AuthScope.ANY_PORT, authentications); // Use preemptive authorisation if no other authorisation has been established builder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme(), isPreemptiveEnabled(authentications))); } }
private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) { Credentials httpCredentials; for (Authentication authentication : authentications) { String scheme = getAuthScheme(authentication); PasswordCredentials credentials = getPasswordCredentials(authentication); if (authentication instanceof AllSchemesAuthentication) { NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials); httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain()); credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials); LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM); } httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()); credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials); LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme); } }
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) { HttpContext httpContext = new HttpClientContext(); if (cookieStore != null) { httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); } if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()), new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword())); httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider); } return httpContext; }
@Override public void setAuth(SensorThingsService service) { try { CredentialsProvider credsProvider = new BasicCredentialsProvider(); URL url = service.getEndpoint().toURL(); credsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue())); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); service.setClient(httpclient); } catch (MalformedURLException ex) { LOGGER.error("Failed to initialise basic auth.", ex); } }
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); }
private HttpClientContext prepareContext() { HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http"); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword()); credsProvider.setCredentials(AuthScope.ANY, credentials); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); return context; }
@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(username, password)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
private Map put(String url, String data) throws IOException, HttpException { Map<String,Object> map = null; CredentialsProvider credentials = credentialsProvider(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentials) .build(); try { HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-Type", "application/json"); HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8")); httpPut.setEntity(entity); System.out.println("Executing request " + httpPut.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPut); try { LOG.debug("----------------------------------------"); LOG.debug((String)response.getStatusLine().getReasonPhrase()); String responseBody = EntityUtils.toString(response.getEntity()); LOG.debug(responseBody); Gson gson = new Gson(); map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass()); LOG.debug(responseBody); } finally { response.close(); } } finally { httpclient.close(); } return map; }
public ElasticBulkSender(String user, String password, HttpHost... hosts) { this.user = user; this.password = password; this.hosts = hosts; this.restClient = RestClient.builder(hosts) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { if (!Strings.isBlank(user)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } else { return httpClientBuilder; } } }) .build(); }
private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { String schemeName = authScheme.getSchemeName(); if (this.log.isDebugEnabled()) { this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host); } AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setState(AuthProtocolState.SUCCESS); authState.update(authScheme, creds); } else { this.log.debug("No credentials for preemptive authentication"); } }
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) { HttpClientBuilder clientBuilder = HttpClients.custom() .useSystemProperties() .setProxy(new HttpHost(proxyHost, proxyPort, "http")); if (credentials != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials); clientBuilder.setDefaultCredentialsProvider(credsProvider); Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName()); } this.client = clientBuilder.build(); } }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" + ".credentials-provider"); HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host"); if (authState.getAuthScheme() == null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName (), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) { prop = decrypt(prop); String proxyHost = prop.getProperty("proxyHost"); int proxyPort = Integer.valueOf(prop.getProperty("proxyPort")); String proxyUserDomain = prop.getProperty("proxyUserDomain"); String proxyUser = prop.getProperty("proxyUser"); String proxyPassword = prop.getProperty("proxyPassword"); HttpClientBuilder builder = HttpClientBuilder.create(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain)); if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) { credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } builder.setProxy(proxy); builder.setDefaultCredentialsProvider(credsProvider); HttpClient.Factory factory = new SimpleHttpClientFactory(builder); return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory); }
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext, ProxyConfiguration proxyConfiguration) { if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) { HttpHost targetHost = new HttpHost(proxyConfiguration.endpoint().getHost(), proxyConfiguration.endpoint().getPort()); final CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setCredentialsProvider(credsProvider); clientContext.setAuthCache(authCache); } }
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext, HttpClientSettings settings) { if (settings.isPreemptiveBasicProxyAuth()) { HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings .getProxyPort()); final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); clientContext.setCredentialsProvider(credsProvider); clientContext.setAuthCache(authCache); } }
@Before public void setUp() throws Exception { /** * 如果es集群安装了x-pack插件则以此种方式连接集群 * 1. java客户端的方式是以tcp协议在9300端口上进行通信 * 2. http客户端的方式是以http协议在9200端口上进行通信 */ Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build(); client = new PreBuiltXPackTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); elasticsearchTemplate = new ElasticsearchTemplate(client); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "changeme")); restClient = RestClient.builder(new HttpHost("localhost",9200,"http")) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }).build(); }
/** * Creates client context. * @param url url * @param cred credentials * @return client context */ public static HttpClientContext createHttpClientContext(URL url, SimpleCredentials cred) { HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(cred.getUserName(),cred.getPassword())); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); return context; }
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { HttpGet httpget = new HttpGet("http://localhost/"); System.out.println("Executing request " + httpget.getRequestLine()); Future<HttpResponse> future = httpclient.execute(httpget, null); HttpResponse response = future.get(); System.out.println("Response: " + response.getStatusLine()); System.out.println("Shutting down"); } finally { httpclient.close(); } }
public static void main(String[] args) throws Exception { HttpClientContextFactory ctxFact = new HttpClientContextFactory() { public HttpClientContext create() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"), new UsernamePasswordCredentials("user", "password")); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); return context; } }; HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact); HttpResponse resp = endpoint.exec("rpc.http.version", null, null); if (resp.isIsBinary()) { System.out.println("binary"); System.out.println(resp.getInputStream().getName()); } else { System.out.println(resp.getRpcResponse().getResult()); } }
public DataCiteRESTfullClient(String url, String username, String password) { this.url = url; try { context = HttpClientContext.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username, password)); context.setCredentialsProvider(credsProvider); httpClient = HttpClients.createDefault(); } catch (Exception ioe) { close(); logger.log(Level.SEVERE,"Fail to init Client",ioe); throw new RuntimeException("Fail to init Client", ioe); } }
public ESHttpEventStore(final String identifier, final ThreadFactory threadFactory, final URL url, final CredentialsProvider credentialsProvider, final int longPollSec, final int connectTimeout, final int connectionRequestTimeout, final int socketTimeout) { super(); this.identifier = identifier; this.threadFactory = threadFactory; this.url = url; this.credentialsProvider = credentialsProvider; this.longPollSec = longPollSec; this.connectTimeout = connectTimeout; this.connectionRequestTimeout = connectionRequestTimeout; this.socketTimeout = socketTimeout; this.open = false; this.hostAndPort = url.getHost() + ":" + url.getPort(); this.host = url.getHost(); atomFeedReader = new AtomFeedJsonReader(); }
public BitcoindApiHandler(String host, int port, String protocol, String uri, String username, String password) { this.uri = uri; httpClient = HttpClients.createDefault(); targetHost = new HttpHost(host, port, protocol); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
private HttpClientContext configureContext(CredentialsProvider credentialsProvider, String url) { if (credentialsProvider != null) { try { URL targetUrl = new URL(url); HttpHost targetHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); return context; } catch (MalformedURLException e) { LOG.error("Cannot parse URL '{}'", url, e); } } return null; }
public static String convertMp3(final String mp3Path) throws URISyntaxException, IOException { // get credentials for webservice from application config final String apiKey = SkillConfig.getTranslatorConvertServiceUser(); final String apiPass = SkillConfig.getTranslatorConvertServicePass(); // build uri final String bucketName = SkillConfig.getS3BucketName(); final URIBuilder uri = new URIBuilder(SkillConfig.getTranslatorConvertServiceUrl()).addParameter("bucket", bucketName).addParameter("path", mp3Path); // set up web request final HttpGet httpGet = new HttpGet(uri.build()); httpGet.setHeader("Content-Type", "text/plain"); // set up credentials final CredentialsProvider provider = new BasicCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiKey, apiPass); provider.setCredentials(AuthScope.ANY, credentials); // send request to convert webservice final HttpResponse response = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build().execute(httpGet); //Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); // work on response final HttpEntity entity = response.getEntity(); return IOUtils.toString(entity.getContent(), "UTF-8"); }
/** * Returns HttpClient with basic auth. * * @param userName the user name * @param password the password * @return the http client with basic auth */ private static HttpClient getHttpClientWithBasicAuth( final String userName, final String password ) { // check that userName is not null if ( StringUtils.isBlank( userName ) ) { logger.warn( "In getHttpClientWithBasicAuth, userName is either null or blank." ); return null; } // check that password is not null if ( StringUtils.isBlank( password ) ) { logger.warn( "In getHttpClientWithBasicAuth, password is either null or blank." ); return null; } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( userName, password ); credentialsProvider.setCredentials( AuthScope.ANY, usernamePasswordCredentials ); return HttpClientBuilder.create().setDefaultCredentialsProvider( credentialsProvider ).build(); }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme has been initialized yet if (authState.getAuthScheme() == null) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials credentials = credentialsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (credentials != null) { authState.setAuthScheme(new DiadocAuthScheme()); authState.setCredentials(credentials); } } }
public void setConfigStorage(MtWmConfigStorage configStorage) { this.configStorage = configStorage; String http_proxy_host = configStorage.getHttp_proxy_host(); int http_proxy_port = configStorage.getHttp_proxy_port(); String http_proxy_username = configStorage.getHttp_proxy_username(); String http_proxy_password = configStorage.getHttp_proxy_password(); final HttpClientBuilder builder = HttpClients.custom(); if (StringUtils.isNotBlank(http_proxy_host)) { // 使用代理服务器 if (StringUtils.isNotBlank(http_proxy_username)) { // 需要用户认证的代理服务器 CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password)); builder .setDefaultCredentialsProvider(credsProvider); } httpProxy = new HttpHost(http_proxy_host, http_proxy_port); } httpClient = builder.build(); }
private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthStateHC4 authState, final CredentialsProvider credsProvider) { final String schemeName = authScheme.getSchemeName(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host); } final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName); final Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { authState.setState(AuthProtocolState.CHALLENGED); } else { authState.setState(AuthProtocolState.SUCCESS); } authState.update(authScheme, creds); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "No credentials for preemptive authentication"); } } }
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent("Android-Mms/2.0") .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); }
private static HttpClientBuilder createBuilder() { if (isWinAuthAvailable()) { final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null)) .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null)) .build(); final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider()); return HttpClientBuilder.create() .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry); } else { return HttpClientBuilder.create(); } }
private HttpClient getHttpClient() { Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build(); return httpclient; }
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("lookups.twilio.com", 80), new UsernamePasswordCredentials("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "your_auth_token")); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); try { HttpGet httpget = new HttpGet("https://lookups.twilio.com/v1/PhoneNumbers/+16502530000/?AddOns=payfone_tcpa_compliance&AddOns.payfone_tcpa_compliance.RightPartyContactedDate=20160101"); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpclient.close(); } }
/** * Create the HTTP clean with basic authentication mechanism using specified * credentials * * @param username * Authentication username * @param password * Authentication password * @return */ protected static CloseableHttpClient createHttpClient(String username, String password) { SSLContext sslContext = createSslContext(); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); List<Header> headers = Arrays.asList(header); return HttpClients.custom() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslSocketFactory) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(headers) .build(); }
public static void getConnection(String username, String password, String API, int port, String method, String CollObject) throws ClientProtocolException, IOException { HttpHost targetHost = new HttpHost(API, port, "https"); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); // create a GET method that queries some API operation HttpGet request = new HttpGet(method); try { // execute the operation HttpResponse response = client.execute(targetHost, request); // print the status and the contents of the response System.out.println(response.getStatusLine()); JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8")); JSONArray array = jsonObj.getJSONArray(CollObject); } finally { // release any connection resources used by the method client.close(); } }