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:de.bytefish.fcmjava.client.http.HttpClient.java

public HttpClient(IFcmClientSettings settings) {

    if (settings == null) {
        throw new IllegalArgumentException("settings");
    }//  w  w w .j a  v  a 2 s.c  o  m

    this.settings = settings;

    // Construct the Builder for all Requests:
    this.httpClientBuilder = HttpClientBuilder.create()
            // Build Request Pipeline:
            .addInterceptorFirst(new AuthenticationRequestInterceptor(settings.getApiKey()))
            .addInterceptorLast(new JsonRequestInterceptor())
            .addInterceptorLast(new LoggingRequestInterceptor())
            // Build Response Pipeline:
            .addInterceptorFirst(new LoggingResponseInterceptor())
            .addInterceptorLast(new StatusResponseInterceptor());
}

From source file:io.confluent.support.metrics.utils.WebClient.java

/**
 * Sends a POST request to a web server/*w  w  w  .ja v  a2 s  .co  m*/
 * @param customerId: customer Id on behalf of which the request is sent
 * @param bytes: request payload
 * @param httpPost: A POST request structure
 * @return an HTTP Status code
 */
public static int send(String customerId, byte[] bytes, HttpPost httpPost) {
    int statusCode = DEFAULT_STATUS_CODE;
    if (bytes != null && bytes.length > 0 && httpPost != null && customerId != null) {

        // add the body to the request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("cid", customerId);
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, "filename");
        httpPost.setEntity(builder.build());

        // set the HTTP config
        final RequestConfig config = RequestConfig.custom().setConnectTimeout(requestTimeoutMs)
                .setConnectionRequestTimeout(requestTimeoutMs).setSocketTimeout(requestTimeoutMs).build();

        // send request
        try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
                .build(); CloseableHttpResponse response = httpclient.execute(httpPost)) {
            log.debug("POST request returned {}", response.getStatusLine().toString());
            statusCode = response.getStatusLine().getStatusCode();
        } catch (IOException e) {
            log.debug("Could not submit metrics to Confluent: {}", e.getMessage());
        }
    } else {
        statusCode = HttpStatus.SC_BAD_REQUEST;
    }
    return statusCode;
}

From source file:pl.raszkowski.sporttrackersconnector.garminconnect.AuthorizerIT.java

private void buildHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    CookieStore cookieStore = new BasicCookieStore();

    httpClient = httpClientBuilder.disableRedirectHandling().setDefaultCookieStore(cookieStore).build();
}

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

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String ultimo_mensaje = String.valueOf(request.getSession().getAttribute("ultimo_mensaje"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultimo_mensaje.equals("null") || ultimo_mensaje.isEmpty()) {
            ultimo_mensaje = "-1";
        }/*from ww w .ja  va 2s.  c o  m*/

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("ultimo_mensaje", ultimo_mensaje);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

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

        //parse message data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            MensajeBean ultimo = mensajes.get(mensajes.size() - 1);
            request.getSession().removeAttribute("ultimo_mensaje");
            request.getSession().setAttribute("ultimo_mensaje", ultimo.getId_mensaje());
        }

        if (!ultimo_mensaje.equals("-1")) {
            request.setAttribute("mensajes", mensajes);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_sala = (String) request.getSession().getAttribute("id_sala");
        request.setAttribute("message",
                "Error al intentar actualizar mensajes de Sala " + id_sala + ": " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:feign.httpclient.ApacheHttpClientTest.java

@Test
public void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException {
    final HttpClient httpClient = HttpClientBuilder.create().build();
    final JaxRsTestInterface testInterface = Feign.builder().contract(new JAXRSContract())
            .client(new ApacheHttpClient(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));
}

From source file:de.bytefish.fcmjava.client.tests.FakeFcmClientSettings.java

@Test
public void testFcmClientWithProxySettings() throws Exception {

    // Create Settings:
    IFcmClientSettings settings = new FakeFcmClientSettings();

    // Define the Credentials to be used:
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();

    // Set the Credentials (any auth scope used):
    basicCredentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("your_username", "your_password"));

    // Create the Apache HttpClientBuilder:
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            // Set the Proxy Address:
            .setProxy(new HttpHost("your_hostname", 1234))
            // Set the Authentication Strategy:
            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
            // Set the Credentials Provider we built above:
            .setDefaultCredentialsProvider(basicCredentialsProvider);

    // Create the DefaultHttpClient:
    DefaultHttpClient httpClient = new DefaultHttpClient(settings, httpClientBuilder);

    // Finally build the FcmClient:
    try (IFcmClient client = new FcmClient(settings, httpClient)) {
        // TODO Work with the Proxy ...
    }// ww  w .j a v  a  2s .c  o m
}

From source file:ch.ralscha.extdirectspring_itest.TransactionalServiceTest.java

@Test
public void callClassbasedProxy() throws IOException, JsonParseException, JsonMappingException {

    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {/*from w w w .j a va  2s . co m*/
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        StringEntity postEntity = new StringEntity(
                "{\"action\":\"transactionalService\",\"method\":\"setDate\",\"data\":[103,\"27/04/2012\"],\"type\":\"rpc\",\"tid\":1}",
                "UTF-8");

        post.setEntity(postEntity);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        assertThat(responseString).isNotNull();
        assertThat(responseString.startsWith("[") && responseString.endsWith("]")).isTrue();
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> rootAsMap = mapper
                .readValue(responseString.substring(1, responseString.length() - 1), Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("result")).isEqualTo("103,27.04.2012");
        assertThat(rootAsMap.get("method")).isEqualTo("setDate");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("transactionalService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:tech.aroma.service.ModuleAromaService.java

@Singleton
AlchemyHttp provideAlchemyHttpClient() {
    HttpClient apacheHttpClient = HttpClientBuilder.create().build();

    return AlchemyHttp.newBuilder().usingApacheHttpClient(apacheHttpClient).enableAsyncCallbacks().build();
}

From source file:br.ufg.inf.horus.implementation.service.HttpRequest.java

/**
 * Mtodo que executa o POST.//from   w  w  w.  java2 s  . co  m
 *
 * @see HttpInterface
 * @param url Url para a requisio.
 * @param body Mensagem da requisio.
 * @param log Objeto para exibio de mensagens Log (opcional).
 * @return Resposta da requisio.
 */
@Override
public String request(String url, String body, Log log) throws BsusException {

    BsusValidator.verifyNull(body, " body", log);
    BsusValidator.verifyNull(url, " url", log);

    String resposta = "";

    try {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(body, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost(url);
        post.setEntity(strEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        resposta = EntityUtils.toString(respEntity);

    } catch (IOException e) {
        String message = "Houve um erro ao abrir o documento .xml";
        BsusValidator.catchException(e, message, log);
    } catch (UnsupportedCharsetException e) {
        String message = "O charset 'UTF-8' da mensagem no esta sendo suportado.";
        BsusValidator.catchException(e, message, log);
    } catch (ParseException e) {
        String message = "Houve um erro ao buscar as informaes.";
        BsusValidator.catchException(e, message, log);
    }

    return resposta;
}

From source file:org.opendatakit.briefcase.reused.http.CommonsHttp.java

@Override
public <T> Response<T> execute(Request<T> request) {
    // Always instantiate a new Executor to avoid side-effects between executions
    Executor executor = Executor.newInstance(HttpClientBuilder.create()
            .setDefaultRequestConfig(custom().setCookieSpec(STANDARD).build()).build());
    // Apply auth settings if credentials are received
    request.ifCredentials((URL url, Credentials credentials) -> executor.auth(HttpHost.create(url.getHost()),
            credentials.getUsername(), credentials.getPassword()));
    // get the response body and let the Request map it
    return uncheckedExecute(request, executor).map(request::map);
}