List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:org.wildfly.test.integration.elytron.http.AbstractMechTestBase.java
@Test public void testUnprotected() throws Exception { HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unprotected")); 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.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity())); }//from ww w.jav a 2 s .c o m } }
From source file:com.ibm.connectors.splunklog.SplunkHttpConnection.java
public Properties sendLogEvent(SplunkConnectionData connData, byte[] thePayload, Properties properties) throws ConnectorException { HttpClient myhClient = HttpClients.custom().setConnectionManager(this.cm).build(); HttpClientContext myhContext = HttpClientContext.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(connData.getUser(), connData.getPass())); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(connData.getHost(), Integer.parseInt(connData.getPort()), connData.getScheme()), new BasicScheme()); myhContext.setCredentialsProvider(credsProvider); myhContext.setAuthCache(authCache);/*from w w w .j a va2s .co m*/ HttpPost myhPost = new HttpPost(connData.getSplunkURI()); ByteArrayEntity payload = new ByteArrayEntity(thePayload); try { myhPost.setEntity(payload); HttpResponse response = myhClient.execute(myhPost, myhContext); Integer statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && !connData.getIgnoreSplunkErrors()) { throw new ConnectorException( "Error posting log event to Splunk: " + response.getStatusLine().toString()); } System.out.println(response.getStatusLine().toString()); properties.setProperty("status", String.valueOf(statusCode)); Integer leasedConns = Integer .valueOf(((PoolingHttpClientConnectionManager) this.cm).getTotalStats().getLeased()); properties.setProperty("conns_leased", leasedConns.toString()); Integer availConns = Integer .valueOf(((PoolingHttpClientConnectionManager) this.cm).getTotalStats().getAvailable()); properties.setProperty("conns_available", availConns.toString()); } catch (IOException e) { e.fillInStackTrace(); throw new ConnectorException(e.toString()); } return properties; }
From source file:com.ccreanga.bitbucket.rest.client.http.BitBucketHttpExecutor.java
public BitBucketHttpExecutor(String baseUrl, BitBucketCredentials credentials) { this.baseUrl = baseUrl; HttpHost targetHost = HttpHost.create(baseUrl); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(5);/*from w w w . j a va2s .c o m*/ connectionManager.setDefaultMaxPerRoute(4); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword())); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); httpClient = HttpClients.custom().setConnectionManager(connectionManager) .setDefaultCredentialsProvider(credentialsProvider).build(); }
From source file:org.ops4j.pax.web.itest.VirtualHostsTest.java
@Test public void shouldFindResourceOnVirtualHost() 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); httpGet.setHeader("Host", "alias1"); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(200));/*from w w w.j a v a 2s . com*/ String text = EntityUtils.toString(response.getEntity()); assertThat(text, containsString("Hello from Pax Web!")); }
From source file:fi.vm.kapa.identification.client.ProxyClient.java
public ProxyMessageDTO updateSession(Map<String, String> sessionData, String tid, String pid, String logTag) throws InternalErrorException, InvalidRequestException, IOException { String proxyCallUrl = proxyURLBase + tid + "&pid=" + pid; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(proxyCallUrl); postMethod.setHeader(HEADER_TYPE, HEADER_VALUE); Gson gson = new Gson(); postMethod.setEntity(new StringEntity(gson.toJson(sessionData))); HttpContext context = HttpClientContext.create(); CloseableHttpResponse restResponse = httpClient.execute(postMethod, context); ProxyMessageDTO messageDTO = null;//www. ja v a2 s. co m int statusCode = restResponse.getStatusLine().getStatusCode(); if (statusCode == HTTP_INTERNAL_ERROR) { logger.warn("<<{}>> Proxy encountered internal error", logTag); throw new InternalErrorException(); } else { if (statusCode == HTTP_OK) { messageDTO = gson.fromJson(EntityUtils.toString(restResponse.getEntity()), ProxyMessageDTO.class); } else { logger.warn("<<{}>> Failed to build session, Proxy responded with HTTP {}", logTag, statusCode); throw new InvalidRequestException(); } } restResponse.close(); return messageDTO; }
From source file:com.cognifide.qa.bb.aem.AemAuthCookieFactory.java
/** * This method provides browser cookie for authenticating user to AEM instance * * @param url URL to AEM instance, like http://localhost:4502 * @param login Username to use// ww w .ja v a 2 s . com * @param password Password to use * @return Cookie for selenium WebDriver. */ public Cookie getCookie(String url, String login, String password) { if (!cookieJar.containsKey(url)) { HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8")); nameValuePairs.add(new BasicNameValuePair("j_username", login)); nameValuePairs.add(new BasicNameValuePair("j_password", password)); nameValuePairs.add(new BasicNameValuePair("j_validate", "true")); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); if ("true".equals(properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE))) { addProxyCookie(cookieStore); } context.setCookieStore(cookieStore); try { loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context); loginResponse.close(); } catch (IOException e) { LOG.error("Can't get AEM authentication cookie", e); } finally { loginPost.reset(); } Cookie cookie = findAuthenticationCookie(cookieStore.getCookies()); if (cookie != null) { cookieJar.put(url, cookie); } } return cookieJar.get(url); }
From source file:org.georchestra.extractorapp.ws.extractor.csw.MetadataEntity.java
/** * Stores the metadata retrieved from CSW using the request value. * /* w ww . j ava 2 s . com*/ * @param fileName file name where the metadata must be saved. * * @throws IOException */ public void save(final String fileName) throws IOException { InputStream content = null; BufferedReader reader = null; PrintWriter writer = null; try { writer = new PrintWriter(fileName, "UTF-8"); HttpGet get = new HttpGet(this.request.buildURI()); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClientContext localContext = HttpClientContext.create(); // if credentials are actually provided, use them to configure // the HttpClient object. try { if (this.request.getUser() != null && request.getPassword() != null) { Credentials credentials = new UsernamePasswordCredentials(request.getUser(), request.getPassword()); AuthScope authScope = new AuthScope(get.getURI().getHost(), get.getURI().getPort()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); localContext.setCredentialsProvider(credentialsProvider); } } catch (Exception e) { LOG.error( "Unable to set basic-auth on http client to get the Metadata remotely, trying without ...", e); } content = httpclient.execute(get, localContext).getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(content)); String line = reader.readLine(); while (line != null) { writer.println(line); line = reader.readLine(); } } catch (Exception e) { final String msg = "The metadata could not be extracted"; LOG.error(msg, e); throw new IOException(e); } finally { if (writer != null) writer.close(); if (reader != null) reader.close(); if (content != null) content.close(); } }
From source file:com.continuuity.loom.provisioner.mock.MockWorker.java
public MockWorker(String provisionerId, String workerId, String tenantId, String serverUrl, ScheduledExecutorService executorService, long taskMs, long msBetweenTasks, CloseableHttpClient httpClient) { this.provisionerId = provisionerId; this.workerId = workerId; this.tenantId = tenantId; this.executorService = executorService; this.taskMs = taskMs; this.msBetweenTasks = msBetweenTasks; this.finishRequest = new HttpPost(String.format(serverUrl + "/v1/loom/tasks/finish")); this.takeRequest = new HttpPost(serverUrl + "/v1/loom/tasks/take"); this.httpClient = httpClient; this.httpContext = HttpClientContext.create(); }
From source file:com.jaspersoft.studio.data.adapter.JSSBuiltinDataFileServiceFactory.java
@Override public DataFileService createService(JasperReportsContext context, DataFile dataFile) { if (dataFile instanceof RepositoryDataLocation) { return new RepositoryDataLocationService(context, (RepositoryDataLocation) dataFile); }/*from w w w . j a v a 2 s . com*/ if (dataFile instanceof HttpDataLocation) { return new HttpDataService(context, (HttpDataLocation) dataFile) { @Override protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) { HttpClientBuilder clientBuilder = HttpClients.custom(); HttpUtils.setupProxy(clientBuilder); // single connection BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(); clientBuilder.setConnectionManager(connManager); // ignore cookies for now RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); clientBuilder.setDefaultRequestConfig(requestConfig); HttpClientContext clientContext = HttpClientContext.create(); setAuthentication(parameters, clientContext); CloseableHttpClient client = clientBuilder.build(); return client; } }; } return null; }