List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username, String password, boolean preAuth) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); BasicHttpContext httpContext = new BasicHttpContext(); if (preAuth) { AuthCache authCache = new BasicAuthCache(); authCache.put(httpHost, new BasicScheme()); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }//from www . j ava 2s . c o m return httpContext; } return null; }
From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java
public static <SkdsResponse extends BaseResponse> SkdsResponse postJsonRequest(BaseRequest request, Class<SkdsResponse> responseClass) throws IllegalStateException, IOException { SkdsResponse response = null;/*from www . j a v a 2 s .com*/ InputStream respIs = null; DefaultHttpClient httpclient = null; try { HttpHost targetHost = new HttpHost(HOST_NAME, PORT, "http"); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(USER, PWD)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpPost httppost = new HttpPost("/alfresco/service" + request.getJSONUrl() + ".json?requestType=json"); String req = request.toJSON(); ByteArrayEntity body = new ByteArrayEntity(req.getBytes()); httppost.setEntity(body); HttpResponse resp = httpclient.execute(targetHost, httppost, localcontext); HttpEntity entityResp = resp.getEntity(); respIs = entityResp.getContent(); response = TemplateUtils.Encoding.deserializeJSON(responseClass, respIs); EntityUtils.consume(entityResp); // } catch(Exception e) { // String message = e.getMessage(); // if ( StringUtils.isBlank(message) ) { // message = e.toString(); // } // tracer.error(message, e); // throw new RuntimeException(message, e); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } IOUtils.closeQuietly(respIs); } return response; }
From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java
/** * Http Post Request.// ww w .ja va2s .c o m * @param url Target URL to POST to. * @param body Body to be sent with the post. * @param credentials Credentials to use for basic auth. * @return Body of post returned. * @throws Exception */ private static String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpPost httpPost = new HttpPost(url); AuthCache authCache = new BasicAuthCache(); HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort()); authCache.put(targetHost, new BasicScheme()); final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache); httpPost.setEntity(new StringEntity(body)); HttpResponse response = client.execute(httpPost, context); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String responseBody = entity != null ? EntityUtils.toString(entity) : null; if (status >= 400) { Exception e = new Exception(String.format( "POST request to %s failed with status code: %d. Response: %s", url, status, responseBody)); logger.error(e.getMessage()); throw e; } logger.debug("Status: " + status); return responseBody; }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static HttpContext getPreemptiveContext(HttpHost targetHost) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext; }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java
@VisibleForTesting static RestTemplate buildRestTemplate(String adminUri, String user, String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... // auth cache BasicScheme basicAuth = new BasicScheme(); URI uri;//from w w w . j a v a2 s.c om try { uri = new URI(adminUri); } catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return localContext; } }); restTemplate.setMessageConverters( Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter())); return restTemplate; }
From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java
/** * @param solraccount eventual user name used to authenticate on the target Solr * @param solraccount eventual password used to authenticate on the target Solr * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted * @param maxBytesPerReponse//from w w w . j av a 2 s . co m * maximum acceptable decompressed size in bytes for a response from * the remote Solr server. Negative value or Long.MAX_VALUE means no * limit. * @return a new apache HttpClient instance usable as a custom http client by SolrJ */ private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u, final String solraccount, final String solrpw, final String host, final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) { /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). * Upgrade only when Solr implementation will become compatible */ org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient( CONNECTION_MANAGER) { @Override protected HttpContext createHttpContext() { HttpContext context = super.createHttpContext(); AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol()); authCache.put(targetHost, basicAuth); context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache); if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) { context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY); } this.setHttpRequestRetryHandler( new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry return context; } }; org.apache.http.params.HttpParams params = result.getParams(); /* Set the maximum time to establish a connection to the remote server */ org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout); /* Set the maximum time between data packets reception one a connection has been established */ org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout); /* Set the maximum time to get a connection from the shared connections pool */ HttpClientParams.setConnectionManagerTimeout(params, timeout); result.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws IOException { if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING)) request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP); if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT } }); result.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); if (solraccount != null && !solraccount.isEmpty()) { org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(solraccount, solrpw)); result.setCredentialsProvider(credsProvider); } if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) { /* * Add in last position the eventual interceptor limiting the response size, so * that this is the decompressed amount of bytes that is considered */ result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse), result.getResponseInterceptorCount()); } return result; }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * For Basic auth, configure the context to do pre-emptive auth with the * credentials given./*from ww w . j ava 2 s. c om*/ * @param httpContext The context in use for the requests. * @param serverURI The RTC server we will be authenticating against * @param userId The userId to login with * @param password The password for the User * @param listener A listen to log messages to, Not required * @throws IOException Thrown if anything goes wrong */ private static void handleBasicAuthChallenge(HttpClientContext httpContext, String serverURI, String userId, String password, TaskListener listener) throws IOException { URI uri; try { uri = new URI(serverURI); } catch (URISyntaxException e) { throw new IOException(Messages.HttpUtils_invalid_server(serverURI), e); } HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(userId, password)); httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider); // 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(target, basicAuth); // Add AuthCache to the execution context httpContext.setAuthCache(authCache); }
From source file:com.github.avarabyeu.restendpoint.http.PreemptiveAuthInterceptor.java
/** * Adds provided auth scheme to the client if there are no another provided * auth schemes/*from w w w.ja va 2 s.c om*/ */ @Override public final void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); } }
From source file:org.openscore.content.httpclient.build.ContextBuilder.java
public HttpClientContext build() { if (StringUtils.isEmpty(preemptiveAuth)) { preemptiveAuth = "true"; }/*www. j av a 2s . com*/ HttpClientContext context = HttpClientContext.create(); if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth)) { AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authSchemeLookup.lookup(authTypes.iterator().next()).create(context)); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); } return context; }
From source file:io.cloudslang.content.httpclient.build.ContextBuilder.java
public HttpClientContext build() { if (StringUtils.isEmpty(preemptiveAuth)) { preemptiveAuth = "true"; }//from w w w .j a v a 2 s.c om HttpClientContext context = HttpClientContext.create(); if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth) && !authTypes.contains(AuthTypes.ANONYMOUS)) { AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authSchemeLookup.lookup(authTypes.iterator().next()).create(context)); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); } return context; }