org.apache.http.HttpHost Java Examples
The following examples show how to use
org.apache.http.HttpHost.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JfDemoESPlugin.java From jframe with Apache License 2.0 | 8 votes |
private void startRestClient() { try { HttpHost[] hosts = new HttpHost[] { // new HttpHost("10.132.161.173", 30002, "http") new HttpHost("127.0.0.1", 9200, "http") }; client = RestClient.builder(hosts).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder.setConnectTimeout(2000).setSocketTimeout(10000); } }).setMaxRetryTimeoutMillis(10000).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setMaxConnPerRoute(100).setMaxConnTotal(200); // return httpClientBuilder // .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build()); } }).build(); } catch (Exception e) { LOG.error(e.getMessage(), e.fillInStackTrace()); } }
Example #2
Source File: CachingHttpClient.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
private boolean alreadyHaveNewerCacheEntry(HttpHost target, HttpRequest request, HttpResponse backendResponse) throws IOException { HttpCacheEntry existing = null; try { existing = responseCache.getCacheEntry(target, request); } catch (IOException ioe) { // nop } if (existing == null) return false; Header entryDateHeader = existing.getFirstHeader("Date"); if (entryDateHeader == null) return false; Header responseDateHeader = backendResponse.getFirstHeader("Date"); if (responseDateHeader == null) return false; try { Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date responseDate = DateUtils.parseDate(responseDateHeader .getValue()); return responseDate.before(entryDate); } catch (DateParseException e) { } return false; }
Example #3
Source File: HttpDispatcher.java From sana.mobile with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static HttpDispatcher getInstance(String uri, Credentials credentials) { HttpDispatcher dispatcher = new HttpDispatcher(new HttpHost(uri), new BasicHttpContext()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope( dispatcher.host.getHostName(), dispatcher.host.getPort()); credsProvider.setCredentials(authScope, credentials); ((DefaultHttpClient) dispatcher.client).getCredentialsProvider().setCredentials( authScope, credentials); return dispatcher; }
Example #4
Source File: PreemptiveAuth.java From verigreen with Apache License 2.0 | 6 votes |
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); Credentials creds; if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { creds = credsProvider.getCredentials(new AuthScope( targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, creds); } } }
Example #5
Source File: SearchProxyController.java From elasticsearch with Apache License 2.0 | 6 votes |
@RequestMapping("/_search") public ResponseEntity<InputStreamResource> search(@RequestParam("q") String query, @RequestHeader(value = "X-ElasticSearch-Host", required = false) String elasticSearchHost) throws IOException { HttpHost httpHost = null; Collection<Task> tasks = scheduler.getTasks().values(); Stream<HttpHost> httpHostStream = tasks.stream().map(task -> new HttpHost(task.getHostname(), task.getClientAddress().getPort())); if (elasticSearchHost != null) { httpHost = httpHostStream.filter(host -> host.toHostString().equalsIgnoreCase(elasticSearchHost)).findAny().get(); } else { httpHost = httpHostStream.skip(RandomUtils.nextInt(0, tasks.size())).findAny().get(); } HttpResponse esSearchResponse = httpClient.execute(httpHost, new HttpGet("/_search?q=" + URLEncoder.encode(query, "UTF-8"))); InputStreamResource inputStreamResource = new InputStreamResource(esSearchResponse.getEntity().getContent()); return ResponseEntity.ok() .contentLength(esSearchResponse.getEntity().getContentLength()) .contentType(MediaType.APPLICATION_JSON) .header("X-ElasticSearch-host", httpHost.toHostString()) .body(inputStreamResource); }
Example #6
Source File: ElasticsearchCollector.java From Quicksql with MIT License | 6 votes |
private static RestClient connect(Map<String, Integer> coordinates, Map<String, String> userConfig) { Objects.requireNonNull(coordinates, "coordinates"); Preconditions.checkArgument(! coordinates.isEmpty(), "no ES coordinates specified"); final Set<HttpHost> set = new LinkedHashSet<>(); for (Map.Entry<String, Integer> entry : coordinates.entrySet()) { set.add(new HttpHost(entry.getKey(), entry.getValue())); } final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userConfig.getOrDefault("esUser", "none"), userConfig.getOrDefault("esPass", "none"))); return RestClient.builder(set.toArray(new HttpHost[0])) .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .setMaxRetryTimeoutMillis(300000).build(); }
Example #7
Source File: SPARQLProtocolSession.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected void setUsernameAndPasswordForUrl(String username, String password, String url) { if (username != null && password != null) { logger.debug("Setting username '{}' and password for server at {}.", username, url); java.net.URI requestURI = java.net.URI.create(url); String host = requestURI.getHost(); int port = requestURI.getPort(); AuthScope scope = new AuthScope(host, port); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(scope, cred); httpContext.setCredentialsProvider(credsProvider); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost httpHost = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); authCache.put(httpHost, basicAuth); httpContext.setAuthCache(authCache); } else { httpContext.removeAttribute(HttpClientContext.AUTH_CACHE); httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER); } }
Example #8
Source File: URLRespectsRobotsTest.java From BUbiNG with Apache License 2.0 | 6 votes |
@Test public void test4xxSync() throws Exception { proxy = new SimpleFixedHttpProxy(); URI robotsURL = URI.create("http://foo.bor/robots.txt"); proxy.addNon200(robotsURL, "HTTP/1.1 404 Not Found\n", "# goodguy can do anything\n" + "User-agent: goodguy\n" + "Disallow:\n\n" + "# every other guy can do nothing\n" + "User-agent: *\n" + "Disallow: /\n" ); proxy.start(); HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false); FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this)); fetchData.fetch(robotsURL, httpClient, null, null, true); assertEquals(0, URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy").length); assertEquals(0, URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy foo").length); }
Example #9
Source File: NiciraNvpApiTest.java From cosmic with Apache License 2.0 | 6 votes |
@Test public void testCreateSecurityProfile() throws Exception { final CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); final NiciraNvpApi api = buildApi(httpClient); final SecurityProfile actualSecProfile = api.createSecurityProfile(new SecurityProfile()); assertThat("Wrong Uuid in the newly created SecurityProfile", actualSecProfile, hasProperty("uuid", equalTo(UUID))); assertThat("Wrong Href in the newly created SecurityProfile", actualSecProfile, hasProperty("href", equalTo(HREF))); assertThat("Wrong Schema in the newly created SecurityProfile", actualSecProfile, hasProperty("schema", equalTo(SCHEMA))); verify(response, times(1)).close(); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); }
Example #10
Source File: HttpManagement.java From gerbil with GNU Affero General Public License v3.0 | 6 votes |
/** * Creates a HttpClientBuilder with the default settings of GERBIL. * * @return a HttpClientBuilder with the default settings of GERBIL. */ public HttpClientBuilder generateHttpClientBuilder() { HttpClientBuilder builder = HttpClientBuilder.create(); builder.setUserAgent(userAgent); String proxyHost = GerbilConfiguration.getInstance().getString(PROXY_HOST_KEY); int proxyPort = GerbilConfiguration.getInstance().getInt(PROXY_PORT_KEY, DEFAULT_PROXY_PORT); if (proxyHost != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); } // Use a redirect strategy that allows the "direct redirect" of POST requests // without creating a completely new request builder.setRedirectStrategy(new SimpleRedirectStrategy()).build(); return builder; }
Example #11
Source File: UnixConnectionSocketFactory.java From docker-client with Apache License 2.0 | 6 votes |
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { if (!(socket instanceof UnixSocket)) { throw new AssertionError("Unexpected socket: " + socket); } socket.setSoTimeout(connectTimeout); try { socket.getChannel().connect(new UnixSocketAddress(socketFile)); } catch (SocketTimeoutException e) { throw new ConnectTimeoutException(e, null, remoteAddress.getAddress()); } return socket; }
Example #12
Source File: AsyncServiceClient.java From aliyun-tablestore-java-sdk with Apache License 2.0 | 6 votes |
public <Res> void asyncSendRequest( RequestMessage request, ExecutionContext context, ResponseConsumer<Res> consumer, FutureCallback<Res> callback, TraceLogger traceLogger) { Preconditions.checkNotNull(request); Preconditions.checkNotNull(context); addExtraHeaders(request); context.getSigner().sign(request); handleRequest(request, context.getResquestHandlers()); consumer.setContext(context); final HttpHost target = request.getActionUri().getHost(); if (LOG.isDebugEnabled()) { LOG.debug(TRACE_ID_WITH_COLON + traceLogger.getTraceId() + DELIMITER + INTO_HTTP_ASYNC_CLIENT); } traceLogger.addEventTime(INTO_HTTP_ASYNC_CLIENT, System.currentTimeMillis()); httpClient.execute( new OTSRequestProducer(target, request.getRequest(), traceLogger), consumer, callback); }
Example #13
Source File: LibRequestDirector.java From YiBo with Apache License 2.0 | 6 votes |
protected void rewriteRequestURI( final RequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target); request.setURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); request.setURI(uri); } } } catch (URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
Example #14
Source File: MitmproxyJavaTest.java From mitmproxy-java with Apache License 2.0 | 6 votes |
@Test public void NullInterceptorReturnTest() throws InterruptedException, TimeoutException, IOException, UnirestException { List<InterceptedMessage> messages = new ArrayList<>(); MitmproxyJava proxy = new MitmproxyJava(MITMDUMP_PATH, (InterceptedMessage m) -> { messages.add(m); return null; }, 8087, null); proxy.start(); Unirest.setProxy(new HttpHost("localhost", 8087)); Unirest.get("http://appium.io").header("myTestHeader", "myTestValue").asString(); proxy.stop(); assertThat(messages).isNotEmpty(); final InterceptedMessage firstMessage = messages.get(0); assertThat(firstMessage.getRequest().getUrl()).startsWith("http://appium.io"); assertThat(firstMessage.getRequest().getHeaders()).containsOnlyOnce(new String[]{"myTestHeader", "myTestValue"}); assertThat(firstMessage.getResponse().getStatusCode()).isEqualTo(200); }
Example #15
Source File: DefaultFileDownloader.java From flow with Apache License 2.0 | 5 votes |
private HttpClientContext makeLocalContext(URL requestUrl) { // Auth target host HttpHost target = new HttpHost(requestUrl.getHost(), requestUrl.getPort(), requestUrl.getProtocol()); // 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); return localContext; }
Example #16
Source File: UnixFactory.java From rapid with MIT License | 5 votes |
@Override public Socket connectSocket( int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { try { sock.connect(new UnixSocketAddress(socketFile), connectTimeout); } catch (SocketTimeoutException e) { throw new ConnectTimeoutException(e, null, remoteAddress.getAddress()); } return sock; }
Example #17
Source File: ElasticsearchSinkITCase.java From Flink-CEPplus with Apache License 2.0 | 5 votes |
@Override protected ElasticsearchSinkBase<Tuple2<Integer, String>, RestHighLevelClient> createElasticsearchSink( int bulkFlushMaxActions, String clusterName, List<HttpHost> httpHosts, ElasticsearchSinkFunction<Tuple2<Integer, String>> elasticsearchSinkFunction) { ElasticsearchSink.Builder<Tuple2<Integer, String>> builder = new ElasticsearchSink.Builder<>(httpHosts, elasticsearchSinkFunction); builder.setBulkFlushMaxActions(bulkFlushMaxActions); return builder.build(); }
Example #18
Source File: JettyServerFactoryUnitTest.java From tutorials with MIT License | 5 votes |
/** * Sends a default HTTP GET request to the server and returns the response * status code. * * @return the status code of the response * @throws Exception */ private int sendGetRequest() throws Exception { HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT); HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(target, request); return response.getStatusLine().getStatusCode(); }
Example #19
Source File: VSCrawlerRoutePlanner.java From vscrawler with Apache License 2.0 | 5 votes |
@Override protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException { HttpClientContext httpClientContext = HttpClientContext.adapt(context); Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession); if (proxy == null) { return null; } if (log.isDebugEnabled()) { log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort()); } context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy); crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy); if (proxy.getAuthenticationHeaders() != null) { for (Header header : proxy.getAuthenticationHeaders()) { request.addHeader(header); } } if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) { BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider(); httpClientContext.setCredentialsProvider(credsProvider1); credsProvider1.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); } return new HttpHost(proxy.getIp(), proxy.getPort()); }
Example #20
Source File: ExampleServerTest.java From rack-servlet with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { // Silence logging. System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN"); server = new ExampleServer(new RackModule()); server.start(); client = new DefaultHttpClient(); localhost = new HttpHost("localhost", server.getPort()); }
Example #21
Source File: EsDatasetDeleterService.java From occurrence with Apache License 2.0 | 5 votes |
private RestHighLevelClient createEsClient() { HttpHost[] hosts = new HttpHost[config.esHosts.length]; int i = 0; for (String host : config.esHosts) { try { URL url = new URL(host); hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); i++; } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage(), e); } } SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener(); RestClientBuilder builder = RestClient.builder(hosts) .setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder .setConnectTimeout(config.esConnectTimeout) .setSocketTimeout(config.esSocketTimeout)) .setMaxRetryTimeoutMillis(config.esSocketTimeout) .setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS) .setFailureListener(sniffOnFailureListener); RestHighLevelClient highLevelClient = new RestHighLevelClient(builder); esSniffer = Sniffer.builder(highLevelClient.getLowLevelClient()) .setSniffIntervalMillis(config.esSniffInterval) .setSniffAfterFailureDelayMillis(config.esSniffAfterFailureDelay) .build(); sniffOnFailureListener.setSniffer(esSniffer); return highLevelClient; }
Example #22
Source File: WxMpServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { this.wxMpConfigStorage = wxConfigProvider; String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host(); int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port(); String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username(); String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password(); final HttpClientBuilder builder = HttpClients.custom(); if (StringUtils.isNotBlank(http_proxy_host)) { // 使用代理服务器 if (StringUtils.isNotBlank(http_proxy_username)) { // 需要用户认证的代理服务器 CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password)); builder .setDefaultCredentialsProvider(credsProvider); } else { // 无需用户认证的代理服务器 } httpProxy = new HttpHost(http_proxy_host, http_proxy_port); } if (wxConfigProvider.getSSLContext() != null){ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslsf); } httpClient = builder.build(); }
Example #23
Source File: TestHttpClientService.java From jframe with Apache License 2.0 | 5 votes |
public void testJson() { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpHost target = new HttpHost("120.27.182.142", 80, HttpHost.DEFAULT_SCHEME_NAME); HttpRequestBase request = new HttpPost(target.toURI() + "/mry/usr/qryusr"); request.addHeader("Api-Token", "76067"); String data = ""; // ((HttpPost) request).setEntity(new StringEntity(data, // ContentType.create("text/plain", "utf-8"))); CloseableHttpResponse resp = httpClient.execute(request); HttpEntity entity = resp.getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = entity.getContent(); byte[] buf = new byte[32]; int len = 0; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } String str = new String(baos.toByteArray(), "utf-8"); for (byte b : baos.toByteArray()) { System.out.print(b); System.out.print(' '); } Reader reader = new InputStreamReader(entity.getContent(), ContentType.getOrDefault(entity).getCharset()); // TODO decode by mime-type Map<String, String> rspMap = GSON.fromJson(reader, HashMap.class); String usrJson = rspMap.get("usr"); Map<String, Object> usr = GSON.fromJson(usrJson, HashMap.class); System.out.println(usr.get("id").toString() + usr.get("name")); } catch (Exception e) { e.printStackTrace(); } }
Example #24
Source File: ElasticSearchHost.java From core-ng-project with Apache License 2.0 | 5 votes |
public static HttpHost[] parse(String host) { String[] values = Strings.split(host, ','); HttpHost[] hosts = new HttpHost[values.length]; for (int i = 0; i < values.length; i++) { String value = values[i].strip(); hosts[i] = new HttpHost(value, 9200); } return hosts; }
Example #25
Source File: SdkProxyRoutePlanner.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override protected HttpHost determineProxy( final HttpHost target, final HttpRequest request, final HttpContext context) throws HttpException { return doesTargetMatchNonProxyHosts(target) ? null : proxy; }
Example #26
Source File: ActivitiRestClient.java From product-ei with Apache License 2.0 | 5 votes |
private DefaultHttpClient getHttpClient() { HttpHost target = new HttpHost(hostname, port, "http"); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials (new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(USERNAME, PASSWORD)); return httpClient; }
Example #27
Source File: ExtendedConnectionOperator.java From lavaplayer with Apache License 2.0 | 5 votes |
private void complementException( Throwable exception, HttpHost host, InetSocketAddress localAddress, InetSocketAddress remoteAddress, int connectTimeout, InetAddress[] addresses, int currentIndex ) { StringBuilder builder = new StringBuilder(); builder.append("Encountered when opening a connection with the following details:"); appendField(builder, "host", host); appendField(builder, "localAddress", localAddress); appendField(builder, "remoteAddress", remoteAddress); builder.append("\n connectTimeout: ").append(connectTimeout); appendAddresses(builder, "triedAddresses", addresses, index -> index <= currentIndex && addressTypesMatch(localAddress, addresses[index]) ); appendAddresses(builder, "untriedAddresses", addresses, index -> index > currentIndex && addressTypesMatch(localAddress, addresses[index]) ); appendAddresses(builder, "unsuitableAddresses", addresses, index -> !addressTypesMatch(localAddress, addresses[index]) ); exception.addSuppressed(new AdditionalDetails(builder.toString())); }
Example #28
Source File: TracedHttpClient.java From aws-xray-sdk-java with Apache License 2.0 | 5 votes |
@Override protected CloseableHttpResponse doExecute( HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException { // gross hack to call the wrappedClient's doExecute... // see line 67 of Apache's CloseableHttpClient return wrappedClient.execute(httpHost, httpRequest, httpContext); }
Example #29
Source File: StatefulHttpClient.java From BigData-In-Practice with Apache License 2.0 | 5 votes |
public StatefulHttpClient(int sessionTimeOut, int requestTimeOut, HttpHost proxy) { initCookieStore(); this.sessionTimeOut = sessionTimeOut; this.requestTimeOut = requestTimeOut; RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectTimeout(this.requestTimeOut * 1000).setSocketTimeout(this.requestTimeOut * 1000); if (proxy != null) { requestConfigBuilder.setProxy(proxy); } httpclient = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfigBuilder.build()).build(); }
Example #30
Source File: Http4FileProvider.java From commons-vfs with Apache License 2.0 | 5 votes |
private HttpRoutePlanner createHttpRoutePlanner(final Http4FileSystemConfigBuilder builder, final FileSystemOptions fileSystemOptions) { final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions); if (proxyHost != null) { return new DefaultProxyRoutePlanner(proxyHost); } return new SystemDefaultRoutePlanner(ProxySelector.getDefault()); }