Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

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

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:fi.vm.kapa.identification.config.HttpClientConfiguration.java

@Bean
public CloseableHttpClient configuredHttpClient() {
    return HttpClients.custom().setMaxConnPerRoute(maxConnPerRoute).setConnectionManager(connectionManager())
            .build();
}

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception {

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;// w w w.j  ava2s.c o m
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept-Language", "en-US,en;q=0.5");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.setHeader("Accept", "application/json");
        System.out.println("Executing request " + request.getRequestLine());
        System.out.println("Executing request " + Arrays.toString(request.getAllHeaders()));
        StringEntity se = new StringEntity(body);
        request.setEntity(se);
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post body : " + body);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:comsat.sample.jetty.SampleJetty8SslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("Hello World", entity.getBody());
}

From source file:me.ixfan.wechatkit.token.ObtainAccessTokenCallableJob.java

@Override
public AccessToken call() {

    String requestUrl = WECHAT_GET_OBTAIN_ACCESS_TOKEN.replace("${APPID}", AppProperties.get("APPID"))
            .replace("${APPSECRET}", AppProperties.get("APPSECRET"));

    CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(new ObtainTokenRetryHandler())
            .build();/* w ww . j a  v  a  2  s. co  m*/

    HttpUriRequest request = RequestBuilder.get(requestUrl).setCharset(StandardCharsets.UTF_8).build();
    AccessToken accessToken = null;
    try {
        accessToken = httpClient.execute(request, new AccessTokenResponseHandler());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return accessToken;
}

From source file:nl.architolk.ldt.processors.HttpClientProperties.java

public static CloseableHttpClient createHttpClient() throws Exception {
    if (notInitialized) {
        initialize();//from  w ww.  ja  va  2  s  .c o m
    }
    if (sslsf != null) {
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } else {
        return HttpClients.createDefault();
    }
}

From source file:apidemo.APIDemo.java

public static String sendPostJson(String postUrl, String jsonContent, int timeout /*milisecond*/)
        throws Exception {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
            .setConnectTimeout(timeout).build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .build()) {//from   w w  w .j a  v  a 2  s . co  m
        HttpPost httpPost = new HttpPost(postUrl);
        StringEntity input = new StringEntity(jsonContent, "UTF-8");
        input.setContentType("application/json");
        httpPost.setEntity(input);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Failed : HTTP getStatusCode: " + response.getStatusLine().getStatusCode()
                        + " HTTP getReasonPhrase: " + response.getStatusLine().getReasonPhrase());
            }
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())))) {
                String output;
                StringBuilder strBuilder = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    strBuilder.append(output);
                }
                return strBuilder.toString();
            }
        }
    }
}

From source file:com.tremolosecurity.scale.user.ScaleSession.java

@PostConstruct
public void init() {
    try {//from ww  w  .  j a  v  a  2  s .co m
        HttpClientInfo httpci = this.commonConfig.createHttpClientInfo();

        http = HttpClients.custom().setConnectionManager(httpci.getCm())
                .setDefaultRequestConfig(httpci.getGlobalConfig())
                .setHostnameVerifier(new AllowAllHostnameVerifier()).build();

        URL uurl = new URL(commonConfig.getScaleConfig().getServiceConfiguration().getUnisonURL());
        int port = uurl.getPort();

        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        this.login = request.getRemoteUser();
    } catch (Exception e) {
        logger.error("Could not initialize ScaleSession", e);
    }

}

From source file:org.springframework.cloud.contract.wiremock.WireMockRestTemplateConfiguration.java

@Bean
@ConditionalOnClass(SSLContextBuilder.class)
public RestTemplateCustomizer restTemplateCustomizer() {
    return new RestTemplateCustomizer() {
        @Override//from   ww  w.  ja v a2 s  .c  om
        public void customize(RestTemplate restTemplate) {
            HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
                    .getRequestFactory();
            factory.setHttpClient(createSslHttpClient());
        }

        private HttpClient createSslHttpClient() {
            try {
                SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
                                .build(),
                        NoopHostnameVerifier.INSTANCE);
                return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            } catch (Exception ex) {
                throw new IllegalStateException("Unable to create SSL HttpClient", ex);
            }
        }
    };
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testHttpMsg() throws IOException, InterruptedException, ExecutionException {
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    try (final CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .build()) {//w  w w.j  ava2  s.  c  o  m
        final CloseableHttpResponse res = client.execute(httpGet);
        assertEquals(200, res.getStatusLine().getStatusCode());
        assertEquals("text/html", res.getFirstHeader("Content-Type").getValue());
        assertEquals("12", res.getFirstHeader("Content-Length").getValue());
        assertEquals("httpResponse", EntityUtils.toString(res.getEntity()));
    }
}