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.kurento.test.player.PlayerTst.java

@Override
public void run() {
    try {/* w w w  .j  av  a2 s  .  co m*/
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity resEntity = response.getEntity();

        if (interrupt) {
            // Interrupt test
            resEntity.getContent().close();
        } else if (contentType != null) {
            // If not reject test
            final long initTime = new Date().getTime();
            EntityUtils.consume(resEntity);
            final long seconds = (new Date().getTime() - initTime) / 1000 % 60;
            log.info("Play time: " + seconds + " seconds");
        }

        final int responseStatusCode = response.getStatusLine().getStatusCode();
        log.info("ReasonPhrase " + response.getStatusLine().getReasonPhrase());
        log.info("statusCode " + responseStatusCode);
        Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);

        if (expectedHandlerFlow != null) {
            final List<String> realEventList = EventListener.getEventList();
            log.info("Real Event List: " + realEventList);
            Assert.assertArrayEquals(expectedHandlerFlow, realEventList.toArray());
        }

        if (contentType != null && resEntity.getContentType() != null) {
            Header responseContentType = resEntity.getContentType();
            log.info("contentType " + responseContentType.getValue());
            Assert.assertEquals("Content-Type in response header must be " + contentType, contentType,
                    responseContentType.getValue());
        }

    } catch (Exception e) {
        log.error("Exception in Player Test", e);
    }
}

From source file:eu.eexcess.partnerdata.reference.enrichment.DbpediaSpotlight.java

public boolean isEntityDbpediaSpotlight(String word, PartnerdataLogger logger) {
    long startTime = logger.getActLogEntry().getTimeNow();
    try {//w ww . j a va2s  .  c  o m
        String URL = DBPEDIA_URL;
        URL += word.replaceAll(" ", "%20");

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setSocketTimeout(timeout).build();
        HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        //      HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URL);
        request.setHeader("Accept", "text/xml");
        HttpResponse response;

        try {
            response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                //               Set<DbpediaSpotlightResult> entities=XmlParser.getEntitiesDbpediaSpotlightCandidatesXML(this.partnerConfig,is);
                Set<DbpediaSpotlightResult> entities = XmlParser
                        .getEntitiesDbpediaSpotlightAnnotateXML(this.partnerConfig, is, logger);
                is.close();
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightResults(entities.size());
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightServiceCalls(1);
                logger.getActLogEntry().addEnrichmentDbpediaSpotlightServiceCallDuration(startTime);

                return entities.size() > 0;
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (RuntimeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

    return false;

}

From source file:org.opennms.smoketest.AlarmsPageIT.java

@Before
public void createAlarm() throws Exception {
    final EventBuilder builder = new EventBuilder(EventConstants.IMPORT_FAILED_UEI, "AlarmsPageTest");
    builder.setParam("importResource", "foo");
    final CloseableHttpClient client = HttpClientBuilder.create().build();
    final HttpPost request = new HttpPost(getBaseUrl() + "/opennms/rest/events");
    final Event ev = builder.getEvent();
    final String xml = JaxbUtils.marshal(ev);
    request.setHeader("Authorization", createBasicAuthHeader());
    request.setHeader("Content-Type", "application/xml");
    request.setHeader("Accept", "*/*");
    request.setEntity(new ByteArrayEntity(xml.getBytes("UTF-8")));
    final HttpResponse response = client.execute(request);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != 200 && statusCode != 204) {
        throw new RuntimeException("bad response! " + response.getStatusLine().toString());
    }// ww  w.ja v a2 s .  co m
}

From source file:org.dspace.authority.orcid.Orcidv2.java

/**
 *  Initialize the accessToken that is required for all subsequent calls to ORCID
 *//* w ww.  j a  v a2 s.c  om*/
public void init() throws IOException {
    if (StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(clientSecret)) {
        String authenticationParameters = "?client_id=" + clientId + "&client_secret=" + clientSecret
                + "&scope=/read-public&grant_type=client_credentials";
        HttpPost httpPost = new HttpPost(OAUTHUrl + authenticationParameters);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse getResponse = httpClient.execute(httpPost);

        InputStream is = getResponse.getEntity().getContent();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        JSONObject responseObject = null;
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null && responseObject == null) {
            if (inputStr.startsWith("{") && inputStr.endsWith("}") && inputStr.contains("access_token")) {
                try {
                    responseObject = new JSONObject(inputStr);
                } catch (Exception e) {
                    //Not as valid as I'd hoped, move along
                    responseObject = null;
                }
            }
        }

        if (responseObject != null && responseObject.has("access_token")) {
            accessToken = (String) responseObject.get("access_token");
        }
    }
}

From source file:org.fcrepo.sword.integration.BaseServiceProviderIT.java

@Before
public void setupHttpClient() {
    httpClient = HttpClientBuilder.create().build();
}

From source file:counsil.WebClient.java

public String getFromURL(String ip, int port, String URL) throws IOException {
    String outString = "";

    Integer portInt = port;// ww w. j a  va2s.c om
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2 * 1000).build();

    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    BasicConfigurator.configure();

    try {
        HttpGet httpget = new HttpGet("http://" + ip + ":" + portInt.toString() + URL);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (HttpResponse response) -> {
            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);
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        outString = responseBody;
    } finally {
        httpclient.close();
    }

    return outString;
}

From source file:org.tnova.service.catalog.client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    final int timeout = 5;

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setSocketTimeout(timeout * 1000).build();

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("user1", "user1Pass"));
    final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setDefaultCredentialsProvider(credentialsProvider).build();

    final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
    restTemplate = new RestTemplate(requestFactory);

}

From source file:org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient.java

protected HttpClient createDelegate(IClientConfig config) {
    return HttpClientBuilder.create()
            // already defaults to 0 in builder, so resetting to 0 won't hurt
            .setMaxConnTotal(config.getPropertyAsInteger(CommonClientConfigKey.MaxTotalConnections, 0))
            // already defaults to 0 in builder, so resetting to 0 won't hurt
            .setMaxConnPerRoute(config.getPropertyAsInteger(CommonClientConfigKey.MaxConnectionsPerHost, 0))
            .disableCookieManagement().useSystemProperties() // for proxy
            .build();//from w  w  w  . j a v a  2 s. c o  m
}

From source file:com.predic8.membrane.core.transport.http.IllegalCharactersInURLTest.java

@Test(expected = IllegalArgumentException.class)
public void apacheHttpClient() throws Exception {
    CloseableHttpClient hc = HttpClientBuilder.create().build();
    HttpResponse res = hc.execute(new HttpGet("http://localhost:3027/foo{}"));
    Assert.assertEquals(200, res.getStatusLine().getStatusCode());
}

From source file:org.apache.metamodel.neo4j.Neo4jDataContextTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    if (isConfigured()) {
        final CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        final HttpHost httpHost = new HttpHost(getHostname(), getPort());
        requestWrapper = new Neo4jRequestWrapper(httpClient, httpHost, getUsername(), getPassword(),
                getServiceRoot());//from  ww w  . j a v a 2  s .  c  o  m
    }
}