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

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

Introduction

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

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:org.apache.hyracks.server.test.NCServiceIT.java

private static String getHttp(String url) throws Exception {
    HttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(url);
    int statusCode;
    final HttpResponse httpResponse;
    try {//from  w w  w . j ava 2 s . c om
        httpResponse = client.execute(get);
        statusCode = httpResponse.getStatusLine().getStatusCode();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    String response = EntityUtils.toString(httpResponse.getEntity());
    if (statusCode == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new Exception("HTTP error " + statusCode + ":\n" + response);
    }
}

From source file:org.janusgraph.diskstorage.es.ElasticSearchMultiTypeIndexTest.java

private void clear() throws Exception {
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpHost host = new HttpHost(InetAddress.getByName(esr.getHostname()), ElasticsearchRunner.PORT);
        IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("janusgraph*")));
    }/*from   ww w  . j a  v  a 2 s  .  c o m*/
}

From source file:co.com.soinsoftware.altablero.utils.HttpRequest.java

private Object getResponse(HttpRequestBase httpRequest) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        return httpclient.execute(httpRequest, this);
    }// w  w w.  ja va  2s.  c om
}

From source file:uk.theretiredprogrammer.nbpcglibrary.remoteclient.RemotePersistenceUnitProvider.java

/**
 * Constructor./*  w  w  w.  j a v  a2s  . com*/
 *
 * @param p the connection properties
 */
public RemotePersistenceUnitProvider(Properties p) {
    url = p.getProperty("connection", "");
    httpclient = HttpClients.createDefault();
    operational = pingUrl();
}

From source file:network.thunder.client.communications.HTTPS.java

public boolean connect(String URL) {
    try {/*from w w w  . j  a va 2s .  c o m*/

        RequestConfig.custom().setConnectTimeout(10 * 1000).build();
        httpClient = HttpClients.createDefault();

        httpGet = new HttpGet(URL);
        httpResponse = httpClient.execute(httpGet);

        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:me.ixfan.wechatkit.util.HttpClientUtil.java

/**
 * Send HTTP POST request with body of JSON data.
 * @param url URL of request./*from   ww w .ja  v a  2 s .  c om*/
 * @param jsonBody Body data in JSON.
 * @return JSON object of response.
 * @throws IOException If I/O error occurs.
 */
public static JsonObject sendPostRequestWithJsonBody(String url, String jsonBody) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpUriRequest request = RequestBuilder.post(url).setCharset(Charsets.UTF_8)
            .addHeader("Content-type", "application/json").setEntity(new StringEntity(jsonBody, Charsets.UTF_8))
            .build();
    return httpClient.execute(request, new JsonResponseHandler());
}

From source file:it.valeriovaudi.web.CORSFilterTests.java

@Test
public void filterWithParamiters() throws LifecycleException, ServletException, IOException {
    String webappDirLocation = "src/test/webapp-withParam";
    Tomcat tomcat = TomcatInstanceTestFactory.newTomcatInstance("/testContext", webappDirLocation);
    tomcat.start();//from  ww  w.  j  a v  a 2  s.  c  o  m

    HttpGet httpGet = new HttpGet("http://localhost:8080/testContext/test");
    try (CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse execute = httpClient.execute(httpGet)) {

        assertEquals(CORSFilter.ACCESS_CONTROL_ALLOW_ORIGIN_NAME,
                execute.getFirstHeader(CORSFilter.ACCESS_CONTROL_ALLOW_ORIGIN_NAME).getValue());
        assertEquals(CORSFilter.ACCESS_CONTROL_ALLOW_METHDOS_NAME,
                execute.getFirstHeader(CORSFilter.ACCESS_CONTROL_ALLOW_METHDOS_NAME).getValue());
        assertEquals(CORSFilter.ACCESS_CONTROL_MAX_AGE_NAME,
                execute.getFirstHeader(CORSFilter.ACCESS_CONTROL_MAX_AGE_NAME).getValue());
        assertEquals(CORSFilter.ACCESS_CONTROL_ALLOW_HEADERS_NAME,
                execute.getFirstHeader(CORSFilter.ACCESS_CONTROL_ALLOW_HEADERS_NAME).getValue());
    }
    tomcat.stop();
}

From source file:com.dnastack.bob.service.processor.util.HttpUtils.java

/**
 * Executes GET/POST and obtain the response.
 *
 * @param request request/* w  w  w.  java 2s  . c  o  m*/
 *
 * @return response
 */
public static String executeRequest(HttpRequestBase request) {
    String response = null;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };

        response = httpclient.execute(request, responseHandler);
    } catch (IOException ex) {
        // ignore, response already set to null
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            // ignore
        }
    }

    return response;
}

From source file:com.vsct.dt.strowgr.admin.gui.cli.InitializationCommand.java

@Override
protected void run(Bootstrap bootstrap, Namespace namespace, StrowgrConfiguration strowgrConfiguration)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    NSQHttpClient nsqHttpClient = new NSQHttpClient(
            "http://" + strowgrConfiguration.getNsqProducerFactory().getHost() + ":"
                    + strowgrConfiguration.getNsqProducerFactory().getHttpPort(),
            httpClient);// w ww  .  j a v a2 s  .c o  m
    ConsulRepository consulRepository = strowgrConfiguration.getConsulRepositoryFactory().build();

    // ports
    Optional<Boolean> portsInitialized = consulRepository.initPorts();
    if (portsInitialized.orElse(Boolean.FALSE)) {
        LOGGER.info("key/value for ports is initialized in repository");
    } else {
        LOGGER.warn("key/value for ports can't be initialized (already done?).");
    }

    // initialize haproxy producer queue
    for (String prefix : Arrays.asList("commit_requested_", "delete_requested_")) {
        String topicName = prefix + namespace.getString("haproxy-name");
        if (nsqHttpClient.createTopic(topicName)) {
            LOGGER.info("topic {} has been initialized on nsqd", topicName);
        } else {
            LOGGER.info("topic {} can't be initialized on nsqd", topicName);
        }
    }

    // initialize vip of an haproxy cluster
    if (namespace.get("vip") != null) {
        consulRepository.setHaproxyProperty(namespace.get("haproxy-name"), "vip", namespace.get("vip"));
    }
}

From source file:org.elasticsearch.options.detailederrors.DetailedErrorsDisabledTest.java

@Test
public void testThatErrorTraceParamReturns400() throws Exception {
    // Make the HTTP request
    HttpResponse response = new HttpRequestBuilder(HttpClients.createDefault())
            .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class))
            .addParam("error_trace", "true").method(HttpDeleteWithEntity.METHOD_NAME).execute();

    assertThat(response.getHeaders().get("Content-Type"), is("application/json"));
    assertThat(response.getBody(), is("{\"error\":\"error traces in responses are disabled.\"}"));
    assertThat(response.getStatusCode(), is(400));
}