List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:com.vmware.bdd.manager.ClusterConfigManager.java
private boolean validateLocalRepoURL(String localRepoURL) { boolean succ = true; HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient httpClient = builder.build(); // test the connection to the given url try {//from ww w .jav a 2 s .c o m HttpGet httpGet = new HttpGet(localRepoURL); HttpResponse resp = httpClient.execute(httpGet); StatusLine status = resp.getStatusLine(); if (status.getStatusCode() >= 400) { succ = false; } } catch (Exception e) { succ = false; logger.error(e.getMessage()); } finally { if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { logger.error("Unknown errors in closing the http connection."); } } } return succ; }
From source file:com.gs.tools.doc.extractor.core.DownloadManager.java
private DownloadManager() { logger.info("Init DownloadManager"); cookieStore = new BasicCookieStore(); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultCookieStore(cookieStore); Collection<Header> headers = new ArrayList<Header>(); headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")); headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch")); headers.add(new BasicHeader("Accept-Language", "en-US,en;q=0.8")); // headers.add(new BasicHeader("Accept-Encoding", // "gzip,deflate,sdch")); clientBuilder.setDefaultHeaders(headers); ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom(); connectionConfigBuilder.setBufferSize(10485760); clientBuilder.setDefaultConnectionConfig(connectionConfigBuilder.build()); SocketConfig.Builder socketConfigBuilder = SocketConfig.custom(); socketConfigBuilder.setSoKeepAlive(true); socketConfigBuilder.setSoTimeout(3000000); clientBuilder.setDefaultSocketConfig(socketConfigBuilder.build()); logger.info("Create HTTP Client"); httpClient = clientBuilder.build(); }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis, @Nullable String proxyHostAnPort) { Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()).build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry); connMgr.setDefaultMaxPerRoute(maxConnPerRoute); SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis) .setSoTimeout((int) connTimeoutMillis).build(); connMgr.setDefaultSocketConfig(sCfg); HttpClientBuilder hcb = HttpClientBuilder.create(); hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr); if (proxyHostAnPort == null) { } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) { SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); hcb.setRoutePlanner(rp);/*from w w w.j a va 2 s.co m*/ } else { String[] hostAndPort = proxyHostAnPort.split(":"); Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort); String host = hostAndPort[0]; int port = 80; if (hostAndPort.length > 1) { port = Integer.valueOf(hostAndPort[1]); } HttpHost proxy = new HttpHost(host, port); hcb.setProxy(proxy); } HttpClient httpClient = hcb.build(); return httpClient; }
From source file:org.openstreetmap.josm.plugins.mapillary.actions.MapillarySubmitCurrentChangesetAction.java
@Override public void actionPerformed(ActionEvent event) { String token = Main.pref.get("mapillary.access-token"); if (token == null || token.trim().isEmpty()) { PluginState.notLoggedInToMapillaryDialog(); return;// w w w .j a v a 2s .c o m } PluginState.setSubmittingChangeset(true); MapillaryUtils.updateHelpText(); HttpClientBuilder builder = HttpClientBuilder.create(); HttpPost httpPost = new HttpPost(MapillaryURL.submitChangesetURL().toString()); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("Authorization", "Bearer " + token); JsonArrayBuilder changes = Json.createArrayBuilder(); MapillaryLocationChangeset locationChangeset = MapillaryLayer.getInstance().getLocationChangeset(); for (MapillaryImage image : locationChangeset) { changes.add(Json.createObjectBuilder().add("image_key", image.getKey()).add("values", Json.createObjectBuilder() .add("from", Json.createObjectBuilder().add("ca", image.getCa()) .add("lat", image.getLatLon().getY()).add("lon", image.getLatLon().getX())) .add("to", Json.createObjectBuilder().add("ca", image.getTempCa()) .add("lat", image.getTempLatLon().getY()) .add("lon", image.getTempLatLon().getX())))); } String json = Json.createObjectBuilder().add("change_type", "location").add("changes", changes) .add("request_comment", "JOSM-created").build().toString(); try (CloseableHttpClient httpClient = builder.build()) { httpPost.setEntity(new StringEntity(json)); CloseableHttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { String key = Json.createReader(response.getEntity().getContent()).readObject().getString("key"); synchronized (MapillaryUtils.class) { Main.map.statusLine.setHelpText( String.format("%s images submitted, Changeset key: %s", locationChangeset.size(), key)); } locationChangeset.cleanChangeset(); } } catch (IOException e) { logger.error("got exception", e); synchronized (MapillaryUtils.class) { Main.map.statusLine.setHelpText("Error submitting Mapillary changeset: " + e.getMessage()); } } finally { PluginState.setSubmittingChangeset(false); } }
From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java
private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() { HttpClientBuilder httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override// w ww. j av a 2 s.co m public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); HttpUriRequest currentReq = (HttpUriRequest) context .getAttribute(HttpCoreContext.HTTP_REQUEST); LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI()); if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) { return false; } boolean shouldRetry = (statusCode == 429 || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode)) && executionCount <= MAX_RETRIES; if (!shouldRetry) { throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d", currentReq.getURI(), executionCount, MAX_RETRIES)); } LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode, executionCount, MAX_RETRIES); return true; } @Override public long getRetryInterval() { return RETRY_INTERVAL; } }); httpClientBuilder.setRetryHandler((exception, executionCount, context) -> { HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS); LOGGER.info("Encountered network error. Retrying request {}, Count {} Max is {}", currentReq.getURI(), executionCount, MAX_RETRIES); return executionCount <= MAX_RETRIES; }); httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS) .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build()); return httpClientBuilder.build(); }