List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:org.alfresco.cacheserver.http.CacheHttpClient.java
public void getNodeById(String hostname, int port, String username, String password, String nodeId, String nodeVersion, HttpCallback callback) throws IOException { HttpHost target = new HttpHost(hostname, port, "http"); // 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 HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); CloseableHttpClient httpClient = getHttpClient(target, localContext, username, password); try {/*from w w w.j ava 2 s . c o m*/ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000) .build(); String uri = "http://" + hostname + ":" + port + "/alfresco/api/-default-/private/alfresco/versions/1/contentByNodeId/" + nodeId + "/" + nodeVersion; HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Content-Type", "text/plain"); httpGet.setConfig(requestConfig); System.out.println("Executing request " + httpGet.getRequestLine()); CloseableHttpResponse response = httpClient.execute(target, httpGet, localContext); try { callback.execute(response.getEntity().getContent()); // EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpClient.close(); } }
From source file:gov.nrel.bacnet.consumer.DatabusSender.java
BasicHttpContext setupPreEmptiveBasicAuth(DefaultHttpClient httpclient) { HttpHost targetHost = new HttpHost(host, port, mode); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, key)); // 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 BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext; }
From source file:securitytools.veracode.VeracodeClient.java
/** * Constructs a new VeracodeClient using the specified configuration. * //from w ww .j a v a 2s .c om * @param credentials Credentials used to access Veracode services. * @param clientConfiguration Client configuration for options such as proxy * settings, user-agent header, and network timeouts. */ public VeracodeClient(VeracodeCredentials credentials, ClientConfiguration clientConfiguration) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(TARGET), credentials); AuthCache authCache = new BasicAuthCache(); authCache.put(TARGET, new BasicScheme()); context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); try { client = HttpClientFactory.build(clientConfiguration); } catch (NoSuchAlgorithmException nsae) { throw new VeracodeClientException(nsae.getMessage(), nsae); } }
From source file:org.zenoss.metrics.reporter.HttpPoster.java
private final void postImpl(MetricBatch batch) throws IOException { int size = batch.getMetrics().size(); MetricCollection metrics = new MetricCollection(); metrics.setMetrics(batch.getMetrics()); String json = asJson(metrics); // Add AuthCache to the execution context BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar); if (needsAuth && !authenticated) { AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); authCache.put(targetHost, basicAuth); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }//from w ww . ja va 2 s . c o m post.setEntity(new StringEntity(json, APPLICATION_JSON)); cookieJar.clearExpired(new Date()); httpClient.execute(post, responseHandler, localContext); }
From source file:org.apache.manifoldcf.crawler.connectors.jira.JiraSession.java
private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException { // 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(host, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside); method.addHeader("Accept", "application/json"); try {//from w w w. j a va2 s . c om HttpResponse httpResponse = httpClient.execute(method, localContext); int resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode != 200) throw new IOException( "Unexpected result code " + resultCode + ": " + convertToString(httpResponse)); Object jo = convertToJSON(httpResponse); response.acceptJSONObject(jo); } finally { method.abort(); } }
From source file:org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel.java
public LocalFileModel(final String url, final HttpClientManager.HttpClientBuilderFacade clientBuilder, final String username, final String password, final String hostName, int port) { if (url == null) { throw new NullPointerException(); }/*from w w w. j av a 2s .c o m*/ this.url = url; this.username = username; this.password = password; this.context = HttpClientContext.create(); if (!StringUtil.isEmpty(hostName)) { // Preemptive Basic Authentication HttpHost target = new HttpHost(hostName, port, "http"); // 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 this.context.setAuthCache(authCache); } clientBuilder.setCookieSpec(CookieSpecs.DEFAULT); clientBuilder.setMaxRedirects(10); clientBuilder.allowCircularRedirects(); clientBuilder.allowRelativeRedirect(); }
From source file:com.joyent.http.signature.apache.httpclient.HttpSignatureAuthenticationStrategy.java
@Override public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) { Objects.requireNonNull(authhost, "Authentication host must be present"); Objects.requireNonNull(authScheme, "Authentication scheme must be present"); Objects.requireNonNull(context, "HTTP context must be present"); LOG.debug("HTTP Signature authentication succeeded"); final HttpClientContext clientContext = HttpClientContext.adapt(context); AuthCache authCache = clientContext.getAuthCache(); if (authCache == null) { authCache = new BasicAuthCache(); clientContext.setAuthCache(authCache); }/* ww w . j av a 2 s .c om*/ if (LOG.isDebugEnabled()) { LOG.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost); } authCache.put(authhost, authScheme); }
From source file:org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel.java
/** * @deprecated use {@link LocalFileModel#LocalFileModel(java.lang.String, * org.pentaho.reporting.engine.classic.core.util.HttpClientManager.HttpClientBuilderFacade, * java.lang.String, java.lang.String, java.lang.String, int) }. *///from w ww . ja v a2 s. c o m @Deprecated() public LocalFileModel(final String url, final HttpClient client, final String username, final String password, final String hostName, int port) { if (url == null) { throw new NullPointerException(); } this.url = url; this.username = username; this.password = password; this.client = client; this.context = HttpClientContext.create(); if (!StringUtil.isEmpty(hostName)) { // Preemptive Basic Authentication HttpHost target = new HttpHost(hostName, port, "http"); // 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 this.context.setAuthCache(authCache); } this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); this.client.getParams().setParameter(ClientPNames.MAX_REDIRECTS, Integer.valueOf(10)); this.client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); this.client.getParams().setParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, Boolean.FALSE); }
From source file:org.alfresco.maven.plugin.AbstractRefreshWebappMojo.java
/** * Helper method to make a POST request to the Alfresco Webapp * * @param alfrescoTomcatUrl the URL for the webapp we want to post to * @param postData the POST data that should be sent * @param operation information about the operation we are performing *///from w ww. ja va 2 s . co m private void makePostCall(URL alfrescoTomcatUrl, List<NameValuePair> postData, String operation) { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { // Set up a HTTP POST request to the Alfresco Webapp we are targeting HttpHost targetHost = new HttpHost(alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort(), alfrescoTomcatUrl.getProtocol()); // Set up authentication parameters CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(refreshUsername, refreshPassword)); // Create the HTTP Client we will use to make the call client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // 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 localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Make the call to Refresh the Alfresco Webapp HttpPost httpPost = new HttpPost(alfrescoTomcatUrl.toURI()); response = client.execute(httpPost); if (postData != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8"); httpPost.setEntity(entity); } httpPost.setHeader("Accept-Charset", "iso-8859-1,utf-8"); httpPost.setHeader("Accept-Language", "en-us"); response = client.execute(httpPost); // If no response, no method has been passed if (response == null) { getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg()); return; } // Check if we got a successful response or not int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { getLog().info("Successfull " + operation + " for " + refreshWebappName); } else { String reasonPhrase = response.getStatusLine().getReasonPhrase(); getLog().warn("Failed to " + operation + " for " + refreshWebappName + ". Response status: " + statusCode + ", message: " + reasonPhrase); } } catch (Exception ex) { getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg()); getLog().error("Exception Msg: " + ex.getMessage()); } finally { closeQuietly(response); closeQuietly(client); } }
From source file:org.duracloud.common.web.RestHttpHelper.java
private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity, Map<String, String> headers) throws IOException { if (url == null || url.length() == 0) { throw new IllegalArgumentException("URL must be a non-empty value"); }//w ww . j av a2s . co m HttpRequestBase httpRequest = method.getMethod(url, requestEntity); if (headers != null && headers.size() > 0) { addHeaders(httpRequest, headers); } if (log.isDebugEnabled()) { log.debug(loggingRequestText(url, method, requestEntity, headers)); } org.apache.http.HttpResponse response; if (null != credsProvider) { HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (socketTimeoutMs > -1) { BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(); cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build()); builder.setConnectionManager(cm); } CloseableHttpClient httpClient = buildClient(builder, method); // Use preemptive basic auth URI requestUri = httpRequest.getURI(); HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); response = httpClient.execute(httpRequest, localContext); } else { CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method); response = httpClient.execute(httpRequest); } HttpResponse httpResponse = new HttpResponse(response); if (log.isDebugEnabled()) { log.debug(loggingResponseText(httpResponse)); } return httpResponse; }