List of usage examples for org.apache.http.impl.client HttpClients custom
public static HttpClientBuilder custom()
From source file:org.ops4j.pax.web.itest.VirtualHostsTest.java
@Test public void shouldNotFindResourceOnIncorrectVirtualHost() 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", "noway"); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(404));/*from w w w. ja v a2 s.c om*/ }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlStatusById(String crawlid) { String status = ""; System.out.println("get crawlid"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/*from w ww . ja va 2 s .c o m*/ //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl/" + crawlid); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL + crawlid); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); String result = ""; BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result += inputLine; } in.close(); // TO-DO should be removed in the future and handle it more gracefully result = result.replace("u'", "'"); result = result.replace("'", "\""); JSONObject crawljson = new JSONObject(result); System.out.println("myObject " + crawljson.toString()); status = crawljson.getString("status"); EntityUtils.consume(response.getEntity()); } catch (JSONException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return status; }
From source file:org.phenotips.data.internal.MonarchPatientScorer.java
@Override public void initialize() throws InitializationException { try {/*from ww w. j a v a 2s.c o m*/ this.scorerURL = this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL", "https://monarchinitiative.org/score"); CacheConfiguration config = new LRUCacheConfiguration("monarchSpecificityScore", 2048, 3600); this.cache = this.cacheManager.createNewCache(config); } catch (CacheException ex) { throw new InitializationException("Failed to create cache", ex); } try { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null, NoopHostnameVerifier.INSTANCE); this.client = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) { this.logger.warn("Failed to set custom certificate trust, using the default", ex); this.client = HttpClients.createSystem(); } }
From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java
static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext) throws OIDCClientException, SSLConnectionException { Validate.notNull(httpRequest, "httpRequest"); Validate.notNull(sslContext, "sslContext"); RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build(); CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config) .build();// w ww. ja v a 2 s. c o m CloseableHttpResponse closeableHttpResponse = null; try { HttpRequestBase httpTask = httpRequest.toHttpTask(); closeableHttpResponse = client.execute(httpTask); int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode(); StatusCode statusCode; try { statusCode = StatusCode.parse(statusCodeInt); } catch (ParseException e) { throw new OIDCClientException("failed to parse status code", e); } JSONObject jsonContent = null; HttpEntity httpEntity = closeableHttpResponse.getEntity(); if (httpEntity != null) { ContentType contentType; try { contentType = ContentType.get(httpEntity); } catch (UnsupportedCharsetException | org.apache.http.ParseException e) { throw new OIDCClientException("Error in setting content type in HTTP response."); } if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) { throw new OIDCClientException("unsupported charset: " + contentType.getCharset()); } if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) { throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType()); } String content = EntityUtils.toString(httpEntity); try { jsonContent = JSONUtils.parseJSONObject(content); } catch (ParseException e) { throw new OIDCClientException("failed to parse json response", e); } } closeableHttpResponse.close(); client.close(); return HttpResponse.createJsonResponse(statusCode, jsonContent); } catch (IOException e) { throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e); } }
From source file:no.kantega.publishing.jobs.xmlimport.XMLImportJob.java
@PostConstruct private void init() { int timeout = configuration.getInt("httpclient.connectiontimeout", 10000); String proxyHost = configuration.getString("httpclient.proxy.host"); String proxyPort = configuration.getString("httpclient.proxy.port"); String proxyUser = configuration.getString("httpclient.proxy.username"); String proxyPassword = configuration.getString("httpclient.proxy.password"); if (isNotBlank(proxyHost)) { HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); httpClientBuilder = HttpClients.custom() .setDefaultRequestConfig( RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build()) .setProxy(proxy);// ww w.j av a2 s. c om if (isNotBlank(proxyUser)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } } else { httpClientBuilder = HttpClients.custom().setDefaultRequestConfig( RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout) .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout).build()); } }
From source file:com.ibm.devops.notification.MessageHandler.java
public static void postToWebhook(String webhook, boolean deployableMessage, JSONObject message, PrintStream printStream) { //check webhook if (Util.isNullOrEmpty(webhook)) { printStream.println("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set."); printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); } else {/* w w w .j av a 2 s .c o m*/ // set a 5 seconds timeout RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000) .setConnectTimeout(5000).setConnectionRequestTimeout(5000).build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig) .build(); HttpPost postMethod = new HttpPost(webhook); try { StringEntity data = new StringEntity(message.toString()); postMethod.setEntity(data); postMethod = Proxy.addProxyInformation(postMethod); postMethod.addHeader("Content-Type", "application/json"); if (deployableMessage) { postMethod.addHeader("x-create-connection", "true"); printStream.println("[IBM Cloud DevOps] Sending Deployable Mapping message to webhook:"); printStream.println(message); } CloseableHttpResponse response = httpClient.execute(postMethod); if (response.getStatusLine().toString().matches(".*2([0-9]{2}).*")) { printStream.println("[IBM Cloud DevOps] Message successfully posted to webhook."); } else { printStream.println( "[IBM Cloud DevOps] Message failed, response status: " + response.getStatusLine()); } } catch (IOException e) { printStream.println("[IBM Cloud DevOps] IOException, could not post to webhook:"); e.printStackTrace(printStream); } } }
From source file:com.launchkey.sdk.LaunchKeyClient.java
private static Transport getTransport(Config config, Crypto crypto) { HttpClient httpClient;//from w w w . j a va2 s .c o m if (config.getApacheHttpClient() != null) { httpClient = config.getApacheHttpClient(); } else { int ttlSecs = config.getHttpClientConnectionTTLSecs() == null ? DEFAULT_HTTP_CLIENT_TTL_SECS : config.getHttpClientConnectionTTLSecs(); int maxClients = config.getHttpMaxClients() == null ? DEFAULT_HTTP_CLIENT_MAX_CLIENTS : config.getHttpMaxClients(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(ttlSecs, TimeUnit.SECONDS); connectionManager.setMaxTotal(maxClients); connectionManager.setDefaultMaxPerRoute(maxClients); // Set max per route as there is only one route httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); } String baseUrl = config.getAPIBaseURL() == null ? DEFAULT_API_BASE_URL : config.getAPIBaseURL(); return new ApacheHttpClientTransport(httpClient, baseUrl, crypto); }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSink.java
ApacheHttpSink(final Builder builder, final Logger logger) { this(builder, new SingletonSupplier<>(() -> { final SingletonSupplier<PoolingHttpClientConnectionManager> clientManagerSupplier = new SingletonSupplier<>( () -> {/* w w w . j a va 2s .c om*/ final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(builder._parallelism); connectionManager.setMaxTotal(builder._parallelism); return connectionManager; }); return HttpClients.custom().setConnectionManager(clientManagerSupplier.get()).build(); }), logger); }
From source file:com.cxic.ip.WebUrl.java
public String getResponseStr() { String userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", getClass()); HttpProcessor httpprocessorCopy = null; if (httpprocessorCopy == null) { final HttpProcessorBuilder b = HttpProcessorBuilder.create(); b.addAll(new RequestDefaultHeaders(null), new RequestContent(), new RequestTargetHost(), // new RequestClientConnControl(), new RequestUserAgent(userAgentCopy), new RequestExpectContinue()); b.add(new RequestAddCookies()); b.add(new RequestAcceptEncoding()); b.add(new RequestAuthCache()); b.add(new ResponseProcessCookies()); b.add(new ResponseContentEncoding()); httpprocessorCopy = b.build();//from w w w . j a v a2s . c om } HttpHost proxy = new HttpHost(ip, port, "http"); // DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); CloseableHttpClient httpclient = HttpClients.custom() // .setRoutePlanner(routePlanner) .setProxy(proxy).setHttpProcessor(httpprocessorCopy).build(); String r = ""; HttpGet httpGet = new HttpGet(url); // httpGet.setHeader("GET http://www.stilllistener.com/checkpoint1/test2/ HTTP/1.1",""); // httpGet.setHeader("Host","www.stilllistener.com"); // httpGet.setHeader("User-Agent","Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0"); // httpGet.setHeader("User-Agent","Baiduspider+(+http://www.baidu.com/search/spider.htm)"); // httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); // httpGet.setHeader("Accept-Encoding","gzip, deflate"); // httpGet.setHeader("Referer",url); // httpGet.setHeader("Connection","keep-alive"); // httpGet.setHeader("Cache-Control","max-age=0"); CloseableHttpResponse response1 = null; try { response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); String line = response1.getStatusLine().getReasonPhrase(); // System.out.println(line); if (line.equals("OK")) { r = EntityUtils.toString(entity1); // System.out.println(r); // do something useful with the response body // and ensure it is fully consumed // InputStream in = entity1.getContent(); // System.out.println(EntityUtils.toString(entity1,"GB2312")); //System.out.println(in.toString()); } // do something useful with the response body // and ensure it is fully consumed // InputStream in = entity1.getContent(); // System.out.println(EntityUtils.toString(entity1,"GB2312")); //System.out.println(in.toString()); //System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); response1.close(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return r; }
From source file:org.elasticsearch.http.netty.NettyHttpCompressionIT.java
public void testCanInterpretCompressedRequest() throws Exception { ensureGreen();//ww w . j a v a2 s . c o m ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); // we don't call #disableContentCompression() hence the client will send the content compressed CloseableHttpClient internalClient = HttpClients.custom().addInterceptorFirst(headerExtractor).build(); HttpResponse response = httpClient(internalClient).path("/company/employees/2").method("POST") .body(SAMPLE_DOCUMENT).execute(); assertEquals(201, response.getStatusCode()); assertTrue(headerExtractor.hasContentEncodingHeader()); assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue()); }