org.apache.hc.client5.http.impl.classic.HttpClientBuilder Java Examples

The following examples show how to use org.apache.hc.client5.http.impl.classic.HttpClientBuilder. 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: HttpClient.java    From webdrivermanager with Apache License 2.0 6 votes vote down vote up
public HttpClient(Config config) {
    this.config = config;

    HttpClientBuilder builder = HttpClientBuilder.create()
            .setConnectionManagerShared(true);
    try {
        setupProxyIfRequired(builder);

        HostnameVerifier allHostsValid = (hostname, session) -> hostname
                .equalsIgnoreCase(session.getPeerHost());
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, allHostsValid);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);

        builder.setConnectionManager(cm);
    } catch (Exception e) {
        throw new WebDriverManagerException(e);
    }

    closeableHttpClient = builder.useSystemProperties().build();
}
 
Example #2
Source File: Http5FileProvider.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http5FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
 *
 * @param builder Configuration options builder for HTTP4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @return an {@link HttpClientBuilder} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientBuilder createHttpClientBuilder(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final List<Header> defaultHeaders = new ArrayList<>();
    defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, builder.getUserAgent(fileSystemOptions)));

    final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions)
            ? DefaultConnectionReuseStrategy.INSTANCE
            : (request, response, context) -> false;

    final HttpClientBuilder httpClientBuilder =
            HttpClients.custom()
            .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions))
            .setConnectionManager(createConnectionManager(builder, fileSystemOptions))
            .setConnectionReuseStrategy(connectionReuseStrategy)
            .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions))
            .setDefaultHeaders(defaultHeaders)
            .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));

    if (!builder.getFollowRedirect(fileSystemOptions)) {
        httpClientBuilder.disableRedirectHandling();
    }

    return httpClientBuilder;
}
 
Example #3
Source File: ApacheHttp5ClientTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException {
  final HttpClient httpClient = HttpClientBuilder.create().build();
  final JaxRsTestInterface testInterface = Feign.builder()
      .contract(new JAXRSContract())
      .client(new ApacheHttp5Client(httpClient))
      .target(JaxRsTestInterface.class, "http://localhost:" + server.getPort());

  server.enqueue(new MockResponse().setBody("foo"));
  server.enqueue(new MockResponse().setBody("foo"));

  assertEquals("foo", testInterface.withBody("foo", "bar"));
  final RecordedRequest request1 = server.takeRequest();
  assertEquals("/withBody?foo=foo", request1.getPath());
  assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8));

  assertEquals("foo", testInterface.withoutBody("foo"));
  final RecordedRequest request2 = server.takeRequest();
  assertEquals("/withoutBody?foo=foo", request2.getPath());
  assertEquals("", request2.getBody().readString(StandardCharsets.UTF_8));
}
 
Example #4
Source File: DemoIntegrationAT.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Проверка отдачи статики
 */
@Test
@Order(1)
public void checkStaticContent() throws IOException {
    HttpUriRequest request = new HttpGet("http://localhost:" + port + "/index.html");
    HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
    assertThat(httpResponse.getCode(), equalTo(HttpStatus.SC_OK));
}
 
Example #5
Source File: HttpClient.java    From webdrivermanager with Apache License 2.0 5 votes vote down vote up
private void setupProxyIfRequired(HttpClientBuilder builder)
        throws MalformedURLException, UnsupportedEncodingException {
    String proxy = config.getProxy();
    Optional<HttpHost> proxyHost = createProxyHttpHost(proxy);

    if (proxyHost.isPresent()) {
        builder.setProxy(proxyHost.get());
        Optional<BasicCredentialsProvider> credentialsProvider = createBasicCredentialsProvider(
                proxy, config.getProxyUser(), config.getProxyPass(),
                proxyHost.get());
        if (credentialsProvider.isPresent()) {
            builder.setDefaultCredentialsProvider(
                    credentialsProvider.get());
        }

        String localRepositoryUser = config.getLocalRepositoryUser().trim();
        String localRepositoryPassword = config.getLocalRepositoryPassword()
                .trim();

        if (!isNullOrEmpty(localRepositoryUser)
                && !isNullOrEmpty(localRepositoryPassword)) {
            BasicCredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    localRepositoryUser,
                    localRepositoryPassword.toCharArray());

            AuthScope authScope = new AuthScope(proxyHost.get());

            provider.setCredentials(authScope, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }
    }
}
 
Example #6
Source File: ApacheHttp5Client.java    From feign with Apache License 2.0 4 votes vote down vote up
public ApacheHttp5Client() {
  this(HttpClientBuilder.create().build());
}