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:com.comcast.drivethru.StatusCodeIT.java

public void setupClient() {
    HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
    this.client = new DefaultRestClient("http://httpstat.us/", client);
}

From source file:org.apache.synapse.samples.framework.clients.BasicHttpClient.java

/**
 * Make a HTTP GET request on the specified URL.
 *
 * @param url A valid HTTP URL/*www.j av a2  s .  com*/
 * @return A HttpResponse object
 * @throws Exception If an error occurs while making the HTTP call
 */
public HttpResponse doGet(String url) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpGet get = new HttpGet(url);
        return new HttpResponse(client.execute(get));
    } finally {
        client.close();
    }
}

From source file:org.wildfly.swarm.topology.consul.AdvertisingTestBase.java

protected Map<?, ?> getDefinedServicesAsMap() throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();

    HttpUriRequest request = new HttpGet(servicesUrl);
    CloseableHttpResponse response = client.execute(request);

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    String content = EntityUtils.toString(response.getEntity());
    return mapper.readValue(content, Map.class);
}

From source file:org.mitre.stixwebtools.services.TaxiiService.java

/**
 * Creates a new HttpClient which is needed to make requests from a taxii server.
 * /*from w w  w.  j  a v a 2 s. c o m*/
 * @param proxyUrl
 * @param proxyPort
 * @return 
 */
public HttpClient getTaxiiClient(String proxyUrl, int proxyPort) {

    //We have to make our own CloseableHttpClient so we can use a proxy
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(proxyUrl, proxyPort));
    CloseableHttpClient client = clientBuilder.build();

    HttpClient httpClient = new HttpClient(client);

    return httpClient;

}

From source file:db.dao.Dao.java

public HttpResponse add(String url, Object entity) {
    url = checkIfLocal(url);//  w  ww.j a  v  a2  s . c om

    String usernamepassword = "Pepijn:Mores";
    String encoded = Base64.encodeBase64String(usernamepassword.getBytes());

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost postRequest = new HttpPost(url);
    postRequest.setHeader("content-type", "application/json");
    postRequest.setHeader("Authorization", encoded);

    String entityToJson = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        entityToJson = mapper.writeValueAsString(entity);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex);
    }
    StringEntity jsonString = null;
    try {
        jsonString = new StringEntity(entityToJson);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
    }

    postRequest.setEntity(jsonString);
    HttpResponse response = null;
    try {
        response = client.execute(postRequest);
    } catch (IOException ex) {
        Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
    }
    return response;
}

From source file:ar.edu.ubp.das.src.chat.actions.ActualizarUsuariosAction.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 ultima_actualizacion = String.valueOf(request.getSession().getAttribute("ultima_actualizacion"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultima_actualizacion.equals("null") || ultima_actualizacion.isEmpty()) {
            ultima_actualizacion = String.valueOf(System.currentTimeMillis());
        }//  ww w .java  2s .c  o m

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

        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);
        }

        if (restResp.equals("null") || restResp.isEmpty()) {
            return mapping.getForwardByName("success");
        }
        //parse actualizacion data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<ActualizacionBean>>() {
        }.getType();
        List<ActualizacionBean> actualizaciones = gson.fromJson(restResp, listType);
        List<UsuarioBean> usuarios = actualizaciones.stream()
                .filter(a -> a.getNombre_tipo().equals("UsuarioSala")).map(m -> m.getUsuario())
                .collect(Collectors.toList());

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

        if (!usuarios.isEmpty()) {
            request.setAttribute("usuarios", usuarios);
        }

        return mapping.getForwardByName("success");

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

From source file:com.yahoo.wiki.webservice.application.WikiMain.java

/**
 * Makes the dimensions passthrough./*  w ww .j  av  a 2s.  c  om*/
 * <p>
 * This method sends a lastUpdated date to each dimension in the dimension cache, allowing the health checks
 * to pass without having to set up a proper dimension loader. For each dimension, d, the following query is
 * sent to the /v1/cache/dimensions/d endpoint:
 * {
 *     "name": "d",
 *     "lastUpdated": "2016-01-01"
 * }
 *
 * @param port  The port through which we access the webservice
 *
 * @throws IOException If something goes terribly wrong when building the JSON or sending it
 */
private static void markDimensionCacheHealthy(int port) throws IOException {
    for (DimensionConfig dimensionConfig : new WikiDimensions().getAllDimensionConfigurations()) {
        String dimension = dimensionConfig.getApiName();
        HttpPost post = new HttpPost("http://localhost:" + port + "/v1/cache/dimensions/" + dimension);
        post.setHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(
                String.format("{\n \"name\":\"%s\",\n \"lastUpdated\":\"2016-01-01\"\n}", dimension)));
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = client.execute(post);
        LOG.debug("Mark Dimension Cache Updated Response: ", response);
    }
}

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

@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {/*w ww .j a v  a 2  s .c  o  m*/

        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        InputStream is = getClass().getResourceAsStream("/UploadTestFile.txt");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadService", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));

        builder.addPart("name",
                new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT));

        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);

        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);

        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadService");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jim");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("e-mail")).isEqualTo("test@test.ch");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);

        EntityUtils.consume(resEntity);

        is.close();
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    InputStream is = null;/*from w ww  .  ja va 2  s . c  o  m*/
    CloseableHttpResponse response = null;

    try {
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");
        is = getClass().getResourceAsStream("/UploadTestFile.txt");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadController", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));

        builder.addPart("name",
                new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT));

        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);

        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);

        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadController");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jim");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("email")).isEqualTo("test@test.ch");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);

        EntityUtils.consume(resEntity);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.microsoft.rest.ServiceClient.java

/**
 * Initializes a new instance of the ServiceClient class.
 */
public ServiceClient() {
    this(HttpClientBuilder.create(), Executors.newCachedThreadPool());
}