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:org.jboss.pnc.client.ApacheHttpClient43EngineWithRetry.java

@Override
protected HttpClient createDefaultHttpClient() {
    logger.info("Bootstrapping http engine with request retry handler...");
    final HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    if (defaultProxy != null) {
        requestBuilder.setProxy(defaultProxy);
    }//from  w  w  w.j a  v a2  s. c om
    builder.disableContentCompression();
    builder.setDefaultRequestConfig(requestBuilder.build());

    HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler();
    builder.setRetryHandler(retryHandler);
    return builder.build();
}

From source file:twittercounter4j.internal.HttpClientWrapper.java

private void setHttpClient() {
    httpClient = HttpClientBuilder.create().build();
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

private static int countIndexed() {
    System.out.println("Getting the indexing status");
    int indexed = 0;

    HttpGet statusGet = new HttpGet("http://localhost:9500/unit/_stats");
    try {//from w w  w  . j a  va 2  s  .co m
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        System.out.println("Executing request");
        HttpResponse response = httpclient.execute(statusGet);
        System.out.println("Processing response");
        InputStream isResponse = response.getEntity().getContent();
        BufferedReader isReader = new BufferedReader(new InputStreamReader(isResponse));
        StringBuilder strBuilder = new StringBuilder();
        String readLine;
        while ((readLine = isReader.readLine()) != null) {
            strBuilder.append(readLine);
        }
        isReader.close();
        System.out.println("Done - reading JSON");
        JSONObject esResponse = new JSONObject(strBuilder.toString());
        indexed = esResponse.getJSONObject("indices").getJSONObject("unit").getJSONObject("total")
                .getJSONObject("docs").getInt("count");
        System.out.println("Indexed docs: " + indexed);
        httpclient.close();
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return indexed;
}

From source file:juzu.plugin.jackson.AbstractJacksonRequestTestCase.java

@Test
public void testRequest() throws Exception {
    HttpPost post = new HttpPost(applicationURL() + "/post");
    post.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON));
    HttpClient client = HttpClientBuilder.create().build();
    payload = null;/*from w  w  w .  jav a2  s  .c o  m*/
    client.execute(post);
}

From source file:nl.raja.niruraji.pa.domain.RestClientApacheHttpClient.java

@Override
public String getString(String url) {
    if (url == null || url.isEmpty()) {
        String errorMsg = "The url can't be NULL or empty";
        LOGGER.error(errorMsg);/*w ww  .  j  ava2  s . c o m*/
        throw (new IllegalArgumentException(errorMsg));
    }
    String result = null;
    try {
        // create HTTP Client         
        HttpClient httpClient = HttpClientBuilder.create().build();
        // Create new getRequest with below mentioned URL         
        HttpGet getRequest = new HttpGet(url);
        // Add additional header to getRequest which accepts application/xml data         
        getRequest.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        // Execute your request and catch response         
        HttpResponse response = httpClient.execute(getRequest);
        // Check for HTTP response code: 200 = success         
        if (response.getStatusLine().getStatusCode() != 200) {
            String msg = "API call failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            LOGGER.warn(msg);
            throw new RuntimeException(msg);
        }
        result = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        String msg = "API call failed : " + e.getMessage();
        LOGGER.warn(msg);
    } catch (IOException e) {
        String msg = "Error reading api response : " + e.getMessage();
        LOGGER.error(msg);
    }
    return result;
}

From source file:com.google.cloud.metrics.MetricsSender.java

/**
 * Non-injected constructor for clients that do not want to use dependency injection.
 *
 * @param analyticsId The Google Analytics ID to which reports will be sent.
 *///ww  w.j av  a 2  s . c  o  m
public MetricsSender(String analyticsId) {
    this(analyticsId, HttpClientBuilder.create(), new Random());
}

From source file:ar.com.colo.rest.test.RestletTestSupport.java

public HttpResponse doExecute(HttpUriRequest method) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {/*from www.j  ava2 s .  c  o  m*/
        HttpResponse response = client.execute(method);
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        return response;
    } finally {
        client.close();
    }
}

From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java

public static HttpClientBuilder createHTTPBuilder(URI uri, String username, String password) {
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(/* w  w  w.  j av  a  2  s .  co  m*/
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);
    builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder;
}

From source file:ar.edu.ubp.das.src.chat.actions.SalasJoinAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get user data from session storage
        Gson gson = new Gson();
        Type usuarioType = new TypeToken<LoginTempBean>() {
        }.getType();/*from  ww  w .  j  av  a2  s .  co  m*/
        String sessUser = String.valueOf(request.getSession().getAttribute("user"));
        LoginTempBean user = gson.fromJson(sessUser, usuarioType);

        //prepare http post
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/usuarios-salas/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id_usuario", user.getId()));
        params.add(new BasicNameValuePair("id_sala", form.getItem("id_sala")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpPost.addHeader("Authorization", "BEARER " + request.getSession().getAttribute("token"));
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //get user data from session storage
        String salas = String.valueOf(request.getSession().getAttribute("salas"));
        List<SalaBean> salaList = gson.fromJson(salas, new TypeToken<List<SalaBean>>() {
        }.getType());
        SalaBean actual = salaList.stream().filter(s -> s.getId() == Integer.parseInt(form.getItem("id_sala")))
                .collect(Collectors.toList()).get(0);

        request.getSession().setAttribute("sala", actual);
        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar ingresar a Sala: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}