List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:org.superbiz.AuthBeanTest.java
private String get(final String user, final String password) { final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); final CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(basicCredentialsProvider).build(); final HttpHost httpHost = new HttpHost(webapp.getHost(), webapp.getPort(), webapp.getProtocol()); final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth);//from www . jav a 2s. c om final HttpClientContext context = HttpClientContext.create(); context.setAuthCache(authCache); final HttpGet get = new HttpGet(webapp.toExternalForm() + "servlet"); CloseableHttpResponse response = null; try { response = client.execute(httpHost, get, context); return response.getStatusLine().getStatusCode() + " " + EntityUtils.toString(response.getEntity()); } catch (final IOException e) { throw new IllegalStateException(e); } finally { try { IO.close(response); } catch (final IOException e) { // no-op } } }
From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java
/** * authenticates the context if user and password are set *///from w w w .j a v a 2s . c o m private HttpClientContext initAuthIfNeeded(String url) { HttpClientContext context = HttpClientContext.create(); if (this.user.isEmpty() || this.password.isEmpty()) { log.debug( "http connection without autentication, because no user / password ist known to HttpUtilImpl ..."); return context; } CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password)); URL url4Host; try { url4Host = new URL(url); } catch (MalformedURLException e) { log.error(e.getMessage(), e); return context; } HttpHost targetHost = new HttpHost(url4Host.getHost(), url4Host.getPort(), url4Host.getProtocol()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); return context; }
From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java
/** * Instantiates a new Rest client./* w w w . j ava 2s . co m*/ * * @param host Host name or IP address of the Dell Storage Manager server. * @param port Port the DSM data collector is listening on. * @param user The DSM user name to use. * @param password The DSM password. */ public RestClient(String host, int port, String user, String password) { this.baseUrl = String.format("https://%s:%d/api/rest", host, port); try { // Set up auth handling CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost target = new HttpHost(host, port, "https"); authCache.put(target, basicAuth); // Set up our context httpContext = HttpClientContext.create(); httpContext.setCookieStore(new BasicCookieStore()); httpContext.setAuthCache(authCache); // Create our HTTPS client SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()) .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { // Hopefully default SSL handling is set up LOG.warn("Failed to configure HTTP handling, falling back to default handler."); LOG.debug("Config error: {}", e); this.httpClient = HttpClients.createDefault(); } }
From source file:fr.logfiletoes.config.Unit.java
/** * Initialise ElasticSearch Index ans taile file * @throws IOException /* w w w .ja v a 2 s . com*/ */ public void start() throws IOException { httpclient = HttpClients.createDefault(); context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(getElasticSearch().getUrl()); if (getElasticSearch().getLogin() != null && getElasticSearch().getPassword() != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getElasticSearch().getLogin(), getElasticSearch().getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); context.setCredentialsProvider(credentialsProvider); } CloseableHttpResponse elasticSearchCheck = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check index : \"{0}\"", elasticSearchCheck.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheck.getEntity().getContent())); int statusCodeCheck = elasticSearchCheck.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheck.getEntity()); elasticSearchCheck.close(); if (statusCodeCheck == 404) { // Cration de l'index HttpPut httpPut = new HttpPut(getElasticSearch().getUrl()); CloseableHttpResponse executeCreateIndex = httpclient.execute(httpPut, context); LOG.log(Level.INFO, "Create index : \"{0}\"", executeCreateIndex.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(executeCreateIndex.getEntity().getContent())); EntityUtils.consume(executeCreateIndex.getEntity()); executeCreateIndex.close(); CloseableHttpResponse elasticSearchCheckCreate = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check create index : \"{0}\"", elasticSearchCheckCreate.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheckCreate.getEntity().getContent())); int statusCodeCheckCreate = elasticSearchCheckCreate.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheckCreate.getEntity()); elasticSearchCheckCreate.close(); if (statusCodeCheckCreate != 200) { LOG.log(Level.SEVERE, "unable to create index \"{0}\"", getElasticSearch().getUrl()); throw new IOException("unable to create index \"" + getElasticSearch().getUrl() + "\""); } } else if (elasticSearchCheck.getStatusLine().getStatusCode() != 200) { LOG.severe("unkown error elasticsearch"); throw new IOException("unkown error elasticsearch"); } LOG.log(Level.INFO, "Initialisation ElasticSearch r\u00e9ussi pour {0}", getElasticSearch().getUrl()); tailer = Tailer.create(getLogFile(), new TailerListenerUnit(this, httpclient, context)); }
From source file:com.cloud.utils.rest.RESTServiceConnectorTest.java
@Test public void testExecuteUpdateObject() throws Exception { final TestPojo newObject = new TestPojo(); newObject.setField("newValue"); final String newObjectJson = gson.toJson(newObject); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))) .thenReturn(response);/* ww w. j a v a2 s . c o m*/ final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); connector.executeUpdateObject(newObject, "/somepath"); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Build a HttpClientContext that will preemptively authenticate using Basic Authentication * * @param username Username for credentials * @param password Password for credentials * @param uriForRealm uri used to determine the authentication realm * @return A HttpClientContext that will preemptively authenticate using Basic Authentication */// www . j a v a 2 s. c o m public HttpClientContext getHttpClientContext(String username, String password, URI uriForRealm) { String host = URIUtils.extractHost(uriForRealm).getHostName(); int port = uriForRealm.getPort(); if (port == -1) { if (Constants.HTTP_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) { port = Constants.HTTP_PORT; } else if (Constants.HTTPS_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) { port = Constants.HTTPS_PORT; } } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(host, port, uriForRealm.getScheme()), new BasicScheme()); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); return context; }
From source file:org.ops4j.pax.web.itest.VirtualHostsTest.java
@Test public void shouldNotFindResourceOnDefaultHost() throws Exception { assertThat(servletContext.getContextPath(), is("/cm-static")); String path = String.format("http://localhost:%d/cm-static/hello", getHttpPort()); HttpClientContext context = HttpClientContext.create(); CloseableHttpClient client = HttpClients.custom().build(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(404));/*from ww w .j ava 2 s. com*/ }
From source file:org.wildfly.test.integration.elytron.http.FormMechTestCase.java
@Test @Override// w w w. ja va 2 s .com public void testUnauthorized() throws Exception { HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1")); HttpClientContext context = HttpClientContext.create(); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", LOGIN_PAGE_CONTENT, EntityUtils.toString(response.getEntity())); } } }
From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java
@Override public void ping() throws Exception { // Setup a client with pre-emptive authentication HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {// w ww .java2s.co m AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Issue a simple GET against the Info endpoint HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info"); CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); response.close(); } finally { httpclient.close(); } }
From source file:org.ops4j.pax.web.itest.DigestAuthenticationTest.java
@Test public void shouldDenyAccessOnWrongPassword() throws Exception { assertThat(servletContext.getContextPath(), is("/digest")); String path = String.format("http://localhost:%d/digest/hello", getHttpPort()); HttpClientContext context = HttpClientContext.create(); BasicCredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("mustermann", "wrong")); CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(cp).build(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(401));/*from w w w . j a va 2 s.com*/ }