List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider
public BasicCredentialsProvider()
From source file:edu.lternet.pasta.client.LoginClient.java
/** * Perform a PASTA login operation using the user's credentials. Because there * is not a formal PASTA login method, we will use a simple query for the Data * Package Manager service, which will perform the necessary user * authentication (this step should be replaced with a formal PASTA * "login service method").//from ww w . j a va 2s. c om * * @param uid * The user identifier. * @param password * The user password. * * @return The authentication token as a String object if the login is * successful. */ private String login(String uid, String password) { String token = null; String username = PastaClient.composeDistinguishedName(uid); /* * The following set of code sets up Preemptive Authentication for the HTTP * CLIENT and is done so at the warning stated within the Apache * Http-Components Client tutorial here: * http://hc.apache.org/httpcomponents- * client-ga/tutorial/html/authentication.html#d5e1031 */ // Define host parameters HttpHost httpHost = new HttpHost(this.pastaHost, this.pastaPort, this.pastaProtocol); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // Define user authentication credentials that will be used with the host AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); // 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(httpHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(this.LOGIN_URL); HttpResponse response = null; Header[] headers = null; Integer statusCode = null; try { response = httpClient.execute(httpHost, httpGet, context); headers = response.getAllHeaders(); statusCode = (Integer) response.getStatusLine().getStatusCode(); logger.info("STATUS: " + statusCode.toString()); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.error(e); e.printStackTrace(); } finally { closeHttpClient(httpClient); } if (statusCode == HttpStatus.SC_OK) { String headerName = null; String headerValue = null; // Loop through all headers looking for the "Set-Cookie" header. for (int i = 0; i < headers.length; i++) { headerName = headers[i].getName(); if (headerName.equals("Set-Cookie")) { headerValue = headers[i].getValue(); token = this.getAuthToken(headerValue); } } } return token; }
From source file:com.globo.aclapi.client.ClientAclAPI.java
private static HttpClient newDefaultHttpClient(SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", socketFactory, 443)); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params) { @Override//ww w .ja va 2 s. c om protected HttpContext createHttpContext() { HttpContext httpContext = super.createHttpContext(); AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry(); authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory()); httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry); AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Bearer"); Credentials credentials = new TokenCredentials(""); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(sessionScope, credentials); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); return httpContext; } }; httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector)); return httpClient; }
From source file:com.mediaportal.ampdroid.api.JsonClient.java
private String executeRequest(HttpUriRequest request, int _timeout, String url) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, _timeout); HttpConnectionParams.setSoTimeout(httpParameters, _timeout); HttpConnectionParams.setTcpNoDelay(httpParameters, true); DefaultHttpClient client = new DefaultHttpClient(httpParameters); request.setHeader("User-Agent", Constants.USER_AGENT); if (mUseAuth) { CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(mUser, mPass)); client.setCredentialsProvider(credProvider); }/*from ww w . j a v a 2s.com*/ HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); return response; } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } return null; }
From source file:com.rbmhtechnology.apidocserver.service.RepositoryService.java
@PostConstruct void init() {/*from w ww . j av a 2 s.c om*/ ConstructDocumentationDownloadUrl cacheLoader = new ConstructDocumentationDownloadUrl(); SnapshotRemovalListener removalListener = new SnapshotRemovalListener(); // snapshots will expire 30 minutes after their last construction (same for all) snapshotDownloadUrlCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterWrite(snapshotsCacheTimeoutSeconds, TimeUnit.SECONDS).removalListener(removalListener) .build(cacheLoader); latestVersionCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterWrite(snapshotsCacheTimeoutSeconds, TimeUnit.SECONDS) .build(new MavenXmlVersionRefResolver(MavenVersionRef.LATEST)); releaseDownloadUrlCache = CacheBuilder.newBuilder().maximumSize(1000).build(cacheLoader); releaseVersionCache = CacheBuilder.newBuilder().maximumSize(1000) .build(new MavenXmlVersionRefResolver(RELEASE)); if (localJarStorage == null) { localJarStorage = Files.createTempDir(); } // http client CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (!StringUtils.isEmpty(repositoryUser) && !StringUtils.isEmpty(repositoryPassword)) { credsProvider.setCredentials(new AuthScope(repositoryUrl.getHost(), repositoryUrl.getPort()), new UsernamePasswordCredentials(repositoryUser, repositoryPassword)); } httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); }
From source file:io.github.bonigarcia.wdm.WdmHttpClient.java
private final BasicCredentialsProvider createBasicCredentialsProvider(String proxy, String proxyUser, String proxyPass, HttpHost proxyHost) { URL proxyUrl = determineProxyUrl(proxy); if (proxyUrl == null) { return null; }//from ww w.j a va2 s.c o m try { String username = null; String password = null; // apply env value String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { StringTokenizer st = new StringTokenizer(userInfo, ":"); username = st.hasMoreTokens() ? URLDecoder.decode(st.nextToken(), StandardCharsets.UTF_8.name()) : null; password = st.hasMoreTokens() ? URLDecoder.decode(st.nextToken(), StandardCharsets.UTF_8.name()) : null; } String envProxyUser = System.getenv("HTTPS_PROXY_USER"); String envProxyPass = System.getenv("HTTPS_PROXY_PASS"); username = (envProxyUser != null) ? envProxyUser : username; password = (envProxyPass != null) ? envProxyPass : password; // apply option value username = (proxyUser != null) ? proxyUser : username; password = (proxyPass != null) ? proxyPass : password; if (username == null) { return null; } BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), new UsernamePasswordCredentials(username, password)); return credentialsProvider; } catch (UnsupportedEncodingException e) { throw new RuntimeException("Invalid encoding.", e); } }
From source file:com.servoy.extensions.plugins.http.HttpProvider.java
/** * @param url//w w w . ja va 2s.c o m * @param httpClientName * @param username * @param password * @return */ private String getPageData(String url, String httpClientName, String username, String password) { try { DefaultHttpClient client = getOrCreateHTTPclient(httpClientName, url); HttpGet get = new HttpGet(url); HttpResponse res = client.execute(get); // you can get the status from here... (return code) BasicCredentialsProvider bcp = new BasicCredentialsProvider(); if (username != null) { URL _url = createURLFromString(url); bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()), new UsernamePasswordCredentials(username, password)); client.setCredentialsProvider(bcp); } lastPageEncoding = EntityUtils.getContentCharSet(res.getEntity()); return EntityUtils.toString(res.getEntity()); } catch (Exception e) { Debug.error(e); return "";//$NON-NLS-1$ } }
From source file:org.guvnor.ala.wildfly.access.WildflyClient.java
public int undeploy(String deploymentName) throws WildflyClientException { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, managementPort), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); final HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management"); post.addHeader("X-Management-Client-Name", "GUVNOR-ALA"); // the DMR operation ModelNode operation = new ModelNode(); operation.get("operation").set("remove"); operation.get("address").add("deployment", deploymentName); post.setEntity(new StringEntity(operation.toJSONString(true), APPLICATION_JSON)); try {/*w ww. j av a 2s . com*/ HttpResponse response = httpclient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new WildflyClientException("Error Undeploying App Status Code: " + statusCode); } return statusCode; } catch (IOException ex) { LOG.error("Error Undeploying App : " + ex.getMessage(), ex); throw new WildflyClientException("Error Undeploying App : " + ex.getMessage(), ex); } }
From source file:org.jenkinsci.plugins.fod.FoDAPI.java
private HttpClient getHttpClient() { final String METHOD_NAME = CLASS_NAME + ".getHttpClient"; PrintStream logger = FodBuilder.getLogger(); if (null == this.httpClient) { HttpClientBuilder builder = HttpClientBuilder.create(); if (null != proxyConfig) { String fodBaseUrl = null; if (null != this.baseUrl && !this.baseUrl.isEmpty()) { fodBaseUrl = this.baseUrl; } else { fodBaseUrl = PUBLIC_FOD_BASE_URL; }//from w w w .j a v a 2s . c o m Proxy proxy = proxyConfig.createProxy(fodBaseUrl); InetSocketAddress address = (InetSocketAddress) proxy.address(); HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort(), proxy.address().toString().indexOf("https") != 0 ? "http" : "https"); builder.setProxy(proxyHttpHost); if (null != proxyConfig.getUserName() && !proxyConfig.getUserName().trim().equals("") && null != proxyConfig.getPassword() && !proxyConfig.getPassword().trim().equals("")) { Credentials credentials = new UsernamePasswordCredentials(proxyConfig.getUserName(), proxyConfig.getPassword()); AuthScope authScope = new AuthScope(address.getHostName(), address.getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(authScope, credentials); builder.setDefaultCredentialsProvider(credsProvider); } logger.println(METHOD_NAME + ": using proxy configuration: " + proxyHttpHost.getSchemeName() + "://" + proxyHttpHost.getHostName() + ":" + proxyHttpHost.getPort()); } this.httpClient = builder.build(); } return this.httpClient; }
From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java
@Override public RestConfiguration withAuthentication(String user, String password) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); CredentialsProvider provider = new BasicCredentialsProvider(); URI uri = request.getURI();/*from www .j av a2 s .c o m*/ authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); this.context.setCredentialsProvider(provider); this.context.setAuthCache(authCache); return this; }
From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java
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(/*from www .ja v a 2s .c o m*/ 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(); }