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:io.apiman.gateway.test.PerfOverheadTest.java

/**
 * Send a bunch of GET requests to the given endpoint and measure the response
 * time in millis.//  ww  w .j a va 2 s  .c  o  m
 * @param endpoint
 * @param numIterations
 * @throws Exception 
 */
private static int doTest(String endpoint, int numIterations) throws Exception {
    System.out.print("Testing endpoint " + endpoint + ": \n    ["); //$NON-NLS-1$ //$NON-NLS-2$
    CloseableHttpClient client = HttpClientBuilder.create().build();

    try {
        long totalResponseTime = 0;
        for (int i = 0; i < numIterations; i++) {
            HttpGet get = new HttpGet(endpoint);
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception("Status Code Error: " + response.getStatusLine().getStatusCode()); //$NON-NLS-1$
            }
            response.getAllHeaders();
            IOUtils.toString(response.getEntity().getContent());
            long end = System.currentTimeMillis();
            totalResponseTime += (end - start);
            System.out.print("-"); //$NON-NLS-1$
            if (i % 80 == 0) {
                System.out.println(""); //$NON-NLS-1$
            }
        }
        System.out.println("]  Total=" + totalResponseTime); //$NON-NLS-1$
        return (int) (totalResponseTime / numIterations);
    } finally {
        client.close();
    }
}

From source file:org.fcrepo.integration.ldp.LdpTestSuiteIT.java

protected static HttpClient createClient() {
    return HttpClientBuilder.create().setMaxConnPerRoute(MAX_VALUE).setMaxConnTotal(MAX_VALUE).build();
}

From source file:com.psbk.modulperwalian.Controller.ControllerLogin.java

public JSONObject getDataLogin() {
    JSONObject obj = null;/*from   w w  w.j av a  2  s.  c  om*/
    HttpClient httpClient = HttpClientBuilder.create().build();
    String status = null;
    try {
        String url = getIp() + "login";
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity("{request:{\"username\":\"" + getUsername() + "\","
                + "\"password\":\"" + getPassword() + "\" } }");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        status = EntityUtils.toString(entity, "UTF-8");
        JSONObject result;
        obj = new JSONObject(status);

    } catch (Exception ex) {
        System.out.println("Error karena : " + ex.getMessage());
    }

    return obj;
}

From source file:org.bedework.util.http.HttpUtil.java

public static CloseableHttpClient getClient(final boolean disableRedirects) {
    final HttpClientBuilder bldr = HttpClientBuilder.create();

    if (disableRedirects) {
        bldr.disableRedirectHandling();//from www . j  a  v a2s. c  om
    }

    return bldr.build();
}

From source file:com.predic8.membrane.servlet.test.ReleaseConfigurationTest.java

@Test
public void testReachable() throws ClientProtocolException, IOException {
    String secret = "Web Services";
    HttpClient hc = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(getBaseURL());
    post.setEntity(new StringEntity(secret));
    HttpResponse res = hc.execute(post);
    assertEquals(200, res.getStatusLine().getStatusCode());

    AssertUtils.assertContains(secret, EntityUtils.toString(res.getEntity()));
}

From source file:guru.nidi.loader.url.UrlLoader.java

public UrlLoader(String base, UrlFetcher fetcher, CloseableHttpClient httpClient) {
    this.base = base;
    this.fetcher = fetcher;
    this.client = httpClient == null
            ? HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build()
            : httpClient;/*  www  .j a v  a2  s . c o m*/
}

From source file:org.n52.sor.client.Client.java

/**
 * @param request//from   ww  w  .j a  v a  2 s .  c o  m
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws HttpException
 */
private static XmlObject doSend(String request, String requestMethod)
        throws UnsupportedEncodingException, IOException {
    log.debug("Sending request (first 100 characters): {}",
            request.substring(0, Math.min(request.length(), 100)));

    PropertiesManager pm = PropertiesManager.getInstance();

    // create and set up HttpClient
    try (CloseableHttpClient client = HttpClientBuilder.create().build();) {

        HttpRequestBase method = null;
        if (requestMethod.equals(GET_METHOD)) {
            String sorURL = pm.getServiceEndpointGet();
            log.debug("Client connecting via GET to {}", sorURL);

            HttpGet get = new HttpGet(request);
            method = get;
        } else if (requestMethod.equals(POST_METHOD)) {
            String sorURL = pm.getServiceEndpointPost();
            log.debug("Client connecting via POST to {}", sorURL);
            HttpPost postMethod = new HttpPost(sorURL.toString());

            postMethod.setEntity(
                    new StringEntity(request, PropertiesManager.getInstance().getClientRequestContentType()));

            method = postMethod;
        } else
            throw new IllegalArgumentException("requestMethod not supported!");

        HttpResponse httpResponse = client.execute(method);
        XmlObject response = XmlObject.Factory.parse(httpResponse.getEntity().getContent());

        return response;
    } catch (XmlException e) {
        log.error("Error parsing response.", e);
    }
    return null;
}

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

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String url = "http://25.136.78.82:8080/salas";
        HttpGet getRequest = new HttpGet(url);
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        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);
        }//  ww w. j av a 2 s.co m

        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<SalaBean>>() {
        }.getType();
        List<SalaBean> salas = gson.fromJson(restResp, listType);
        request.getSession().setAttribute("salas", salas);
        return mapping.getForwardByName("success");

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

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Call REST API to submit job to Azure ML for batch predictions
 * @return response from the REST API//from   w  ww.j  a  va  2 s. co  m
 */
public static String besHttpPost() {

    HttpPost post;
    HttpClient client;
    StringEntity entity;

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(apiurl);
        client = HttpClientBuilder.create().build();

        // setup output message by copying JSON body into 
        // apache StringEntity object along with content type
        entity = new StringEntity(jsonBody, HTTP.UTF_8);
        entity.setContentEncoding(HTTP.UTF_8);
        entity.setContentType("text/json");

        // add HTTP headers
        post.setHeader("Accept", "text/json");
        post.setHeader("Accept-Charset", "UTF-8");

        // set Authorization header based on the API key
        post.setHeader("Authorization", ("Bearer " + apikey));
        post.setEntity(entity);

        // Call REST API and retrieve response content
        HttpResponse authResponse = client.execute(post);

        jobId = EntityUtils.toString(authResponse.getEntity()).replaceAll("\"", "");

        return jobId;

    } catch (Exception e) {

        return e.toString();
    }

}

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

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/usuarios-salas/sala/" + sala.getId());

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

        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);
        }//from   w w  w .jav  a 2  s  . c  o  m
        //parse message data from response
        Gson gson = new Gson();
        UsuarioBean[] usrList = gson.fromJson(restResp, UsuarioBean[].class);
        request.setAttribute("usuarios", usrList);

        return mapping.getForwardByName("success");

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

}