Example usage for org.apache.http.impl.client HttpClientBuilder create

List of usage examples for org.apache.http.impl.client HttpClientBuilder create

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder create.

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:HCEngine.java

private CloseableHttpClient createCloseableHttpClient() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties();//from ww  w .j  av a 2 s  .c o m
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    builder.setSSLContext(SSLContext.getDefault());
    CloseableHttpClient hc = builder.build();
    return hc;
}

From source file:com.github.aistomin.jenkins.real.RealJenkins.java

@Override
public String version() throws Exception {
    final Map<String, String> headers = new HashMap<>();
    Executor.newInstance(HttpClientBuilder.create().build()).execute(Request.Post(this.base))
            .handleResponse(new ResponseHandler<Object>() {
                public Object handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    for (final Header header : response.getAllHeaders()) {
                        headers.put(header.getName(), header.getValue());
                    }/*from w w w . j a  v a  2 s.  c  o m*/
                    return response;
                }
            });
    return headers.get("X-Jenkins");
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Before
public void before() throws Exception {
    closeableHttpClient = HttpClientBuilder.create().build();

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }//from w w w  .jav a 2 s.  co  m

    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
    JsonNode steeringNode = objectMapper.readTree(inputStream).get("response").get(0);

    steeringDeliveryServiceId = steeringNode.get("deliveryService").asText();
    Iterator<JsonNode> iterator = steeringNode.get("targets").iterator();
    while (iterator.hasNext()) {
        JsonNode target = iterator.next();
        steeredDeliveryServices.add(target.get("deliveryService").asText());
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext() && deliveryServiceId == null) {
        String dsId = deliveryServices.next();

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);

        if (deliveryServiceNode.has("steeredDeliveryServices")) {
            continue;
        }

        JsonNode dispersionNode = deliveryServiceNode.get("dispersion");

        if (dispersionNode == null || dispersionNode.get("limit").asInt() != 1
                && dispersionNode.get("shuffled").asText().equals("true")) {
            continue;
        }

        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();
        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                deliveryServiceId = dsId;
            }
        }

        if (deliveryServiceId == null) {
            System.out.println("Skipping " + deliveryServiceId + " no http protocol matchset");
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(steeringDeliveryServiceId, not(nullValue()));
    assertThat(steeredDeliveryServices.isEmpty(), equalTo(false));

    resourcePath = "czf.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    jsonNode = objectMapper.readTree(inputStream);

    JsonNode network = jsonNode.get("coverageZones").get(jsonNode.get("coverageZones").fieldNames().next())
            .get("network");

    for (int i = 0; i < network.size(); i++) {
        String cidrString = network.get(i).asText();
        CidrAddress cidrAddress = CidrAddress.fromString(cidrString);
        if (cidrAddress.getNetmaskLength() == 24) {
            byte[] hostBytes = cidrAddress.getHostBytes();
            ipAddressInCoverageZone = String.format("%d.%d.%d.123", hostBytes[0], hostBytes[1], hostBytes[2]);
            break;
        }
    }

    assertThat(ipAddressInCoverageZone.length(), greaterThan(0));
}

From source file:fi.helsinki.moodi.config.MoodleConfig.java

private RestTemplate createRestTemplate(HttpRequestRetryHandler httpRequestRetryHandler) {
    final HttpClient httpClient = HttpClientBuilder.create().setRetryHandler(httpRequestRetryHandler).build();

    final ClientHttpRequestFactory requestFactory = new BufferingClientHttpRequestFactory(
            new HttpComponentsClientHttpRequestFactory(httpClient));

    final RestTemplate restTemplate = new RestTemplate(requestFactory);
    restTemplate.setInterceptors(Collections.singletonList(new RequestTimingInterceptor()));

    restTemplate.setMessageConverters(/*from  w  w  w  .ja v a  2 s.co  m*/
            Lists.newArrayList(new StringHttpMessageConverter(), new FormHttpMessageConverter()));

    return restTemplate;
}

From source file:com.precioustech.fxtrading.oanda.restapi.streaming.OandaStreamingService.java

protected CloseableHttpClient getHttpClient() {
    return HttpClientBuilder.create().build();
}

From source file:ch.cyclops.publish.APICaller.java

/**
 * Perform POST query and return Response
 * @param endpoint to be called//from w  w  w .j  av  a 2  s. com
 * @param object to be passed
 * @return Response object
 * @throws Exception
 */
public APICaller.Response post(URL endpoint, Object object) throws Exception {
    // prepare connection
    HttpClient client = HttpClientBuilder.create().build();

    // create request
    HttpPost request = new HttpPost(endpoint.toURI());
    StringEntity entity = new StringEntity(new Gson().toJson(object));
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.setEntity(entity);

    // execute response
    HttpResponse response = client.execute(request);
    return new Response(IOUtils.toString(response.getEntity().getContent()));
}

From source file:com.kurento.test.recorder.RecorderIT.java

private void testRecord(String handler, int statusCode) throws IOException {
    // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy())
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler);
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File("small");
    URL small = new URL(VideoURLs.map.get("small-webm"));
    FileUtils.copyURLToFile(small, file);
    FileBody fb = new FileBody(file);
    multipartEntity.addPart("file", fb);

    HttpEntity httpEntity = multipartEntity.build();
    post.setEntity(httpEntity);//from  w w  w . j  a va2  s . c o m

    EntityUtils.consume(httpEntity);
    HttpResponse response = client.execute(post);
    final int responseStatusCode = response.getStatusLine().getStatusCode();

    log.info("Response Status Code: {}", responseStatusCode);
    log.info("Deleting tmp file: {}", file.delete());

    Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);
}

From source file:org.qucosa.migration.processors.PurgeFedoraObject.java

private HttpClient prepareHttpClient(String user, String password) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));

    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();
    return client;
}

From source file:io.pivotal.xd.chaoslemur.infrastructure.StandardDirectorUtils.java

private static RestTemplate createRestTemplate(String host, String username, String password,
        Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();//from w  w w . j a  va  2s. co  m

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}

From source file:org.wildfly.elytron.web.undertow.server.BasicAuthenticationTest.java

@Test
public void testUnauthorized() throws Exception {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(server.createUri());

    assertUnauthorizedResponse(httpClient.execute(get));
}