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.apache.DefaultHttpClient.java

public DefaultHttpClient(IFcmClientSettings settings, IJsonSerializer serializer) {
    this(settings, serializer, HttpClientBuilder.create());
}

From source file:com.samebug.clients.search.api.client.RawClient.java

RawClient(@NotNull final Config config) {
    HttpClientBuilder httpBuilder = HttpClientBuilder.create();
    requestConfigBuilder = RequestConfig.custom();
    CredentialsProvider provider = new BasicCredentialsProvider();

    requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout)
            .setConnectionRequestTimeout(500);
    try {/*from w  w  w .j av a 2s.c o  m*/
        IdeHttpClientHelpers.ApacheHttpClient4.setProxyForUrlIfEnabled(requestConfigBuilder, config.serverRoot);
        IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsForUrlIfEnabled(provider, config.serverRoot);
    } catch (Throwable e) {
        // fallback to traditional proxy config for backward compatiblity
        try {
            final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
            final ProxyCredentialsFacade facade = new ProxyCredentialsFacade(proxySettings);
            if (proxySettings != null && proxySettings.USE_HTTP_PROXY
                    && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
                requestConfigBuilder.setProxy(new HttpHost(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT));
                if (proxySettings.PROXY_AUTHENTICATION) {
                    provider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(facade.getLogin(), facade.getPassword()));
                }
            }
        } catch (Throwable ignored) {
            // if even that fails, we cannot do more
        }
    }
    defaultRequestConfig = requestConfigBuilder.build();
    trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build();
    List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>();
    defaultHeaders.add(new BasicHeader("User-Agent", USER_AGENT));
    if (config.apiKey != null)
        defaultHeaders.add(new BasicHeader("X-Samebug-ApiKey", config.apiKey));
    if (config.workspaceId != null)
        defaultHeaders.add(new BasicHeader("X-Samebug-WorkspaceId", config.workspaceId.toString()));

    httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(MaxConnections)
            .setMaxConnPerRoute(MaxConnections).setDefaultCredentialsProvider(provider)
            .setDefaultHeaders(defaultHeaders).build();
    if (config.isApacheLoggingEnabled)
        enableApacheLogging();
}

From source file:org.nuxeo.docusign.core.test.TestDocuSignCallback.java

@Test
public void testReceiveCallbackWithURLParam() throws IOException {
    String url = "http://localhost:18090/docusign/javascript.workflow";
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    post.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/files/callback.xml")));
    HttpResponse response = client.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.evolveum.midpoint.report.impl.ReportNodeUtils.java

public static InputStream executeOperation(String host, String fileName, String intraClusterHttpUrlPattern,
        String operation) throws CommunicationException, SecurityViolationException, ObjectNotFoundException,
        ConfigurationException, IOException {
    fileName = fileName.replaceAll("\\s", SPACE);
    InputStream inputStream = null;
    InputStream entityContent = null;
    LOGGER.trace("About to initiate connection with {}", host);
    try {//from ww  w .  ja v a2 s.c o  m
        if (StringUtils.isNotEmpty(intraClusterHttpUrlPattern)) {
            LOGGER.trace("The cluster uri pattern: {} ", intraClusterHttpUrlPattern);
            URI requestUri = buildURI(intraClusterHttpUrlPattern, host, fileName);
            fileName = URLDecoder.decode(fileName, ReportTypeUtil.URLENCODING);

            LOGGER.debug("Sending request to the following uri: {} ", requestUri);
            HttpRequestBase httpRequest = buildHttpRequest(operation);
            httpRequest.setURI(requestUri);
            httpRequest.setHeader("User-Agent", ReportTypeUtil.HEADER_USERAGENT);
            HttpClient client = HttpClientBuilder.create().build();
            try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpRequest)) {
                HttpEntity entity = response.getEntity();
                Integer statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == HttpStatus.SC_OK) {
                    LOGGER.debug("Response OK, the file successfully returned by the cluster peer. ");
                    if (entity != null) {
                        entityContent = entity.getContent();
                        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = entityContent.read(buffer)) > -1) {
                            arrayOutputStream.write(buffer, 0, len);
                        }
                        arrayOutputStream.flush();
                        inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
                    }
                } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                    if (HttpDelete.METHOD_NAME.equals(operation)) {
                        LOGGER.info("Deletion of the file {} was successful.", fileName);
                    }
                } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                    LOGGER.error("The access to the report with the name {} is forbidden.", fileName);
                    String error = "The access to the report " + fileName + " is forbidden.";
                    throw new SecurityViolationException(error);
                } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                    String error = "The report file " + fileName
                            + " was not found on the originating nodes filesystem.";
                    throw new ObjectNotFoundException(error);
                }
            } catch (ClientProtocolException e) {
                String error = "An exception with the communication protocol has occurred during a query to the cluster peer. "
                        + e.getLocalizedMessage();
                throw new CommunicationException(error);
            }
        } else {
            LOGGER.error(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
            throw new ConfigurationException(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
        }
    } catch (URISyntaxException e1) {
        throw new CommunicationException("Invalid uri syntax: " + e1.getLocalizedMessage());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Unhandled exception when listing nodes");
        LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing nodes", e);
    } finally {
        IOUtils.closeQuietly(entityContent);
    }

    return inputStream;
}

From source file:com.comcast.drivethru.client.DefaultRestClient.java

private static HttpClient defaultClient() {
    return HttpClientBuilder.create()
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(DEFAULT_TIMEOUT).build()).build();
}

From source file:io.github.bonigarcia.wdm.WdmHttpClient.java

private WdmHttpClient(String proxyUrl, String proxyUser, String proxyPass) {
    HttpHost proxyHost = createProxyHttpHost(proxyUrl);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (proxyHost != null) {
        builder.setProxy(proxyHost);//w w  w.ja va2 s  . c om
        BasicCredentialsProvider credentialsProvider = createBasicCredentialsProvider(proxyUrl, proxyUser,
                proxyPass, proxyHost);
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }
    this.httpClient = builder.build();
}

From source file:org.zalando.stups.oauth2.httpcomponents.RoundtripTest.java

@Test
public void simpleRoundTrip() {
    LOG.info("start roundtrip ...");

    AccessTokens accessTokens = Mockito.mock(AccessTokens.class);
    Mockito.when(accessTokens.get(Mockito.eq(SERVICE_ID))).thenReturn(KIO_TEST_TOKEN);

    HttpRequestInterceptor interceptor = new AccessTokensRequestInterceptor(SERVICE_ID, accessTokens);
    HttpClient client = HttpClientBuilder.create().addInterceptorFirst(interceptor).build();

    HttpGet getRequest = new HttpGet("http://localhost:" + port + "/test");
    try {/*from w  w w  . j a va 2 s  .co m*/
        HttpResponse response = client.execute(getRequest);
        String responseString = EntityUtils.toString(response.getEntity());
        Assertions.assertThat(responseString).isEqualTo(KIO_TEST_TOKEN);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    LOG.info("roundtrip ended.");
}

From source file:$.HelloWorldWebScriptIT.java

@Test
    public void testWebScriptCall() throws Exception {
        String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
        String expectedResponse = "Message: 'Hello from JS!' 'HelloFromJava'";

        // Login credentials for Alfresco Repo
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
        provider.setCredentials(AuthScope.ANY, credentials);

        // Create HTTP Client with credentials
        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

        // Execute Web Script call
        try {//from w  w  w.  j a va  2 s.c o  m
            HttpGet httpget = new HttpGet(webscriptURL);
            HttpResponse httpResponse = httpclient.execute(httpget);
            assertEquals("Incorrect HTTP Response Status", HttpStatus.SC_OK,
                    httpResponse.getStatusLine().getStatusCode());
            HttpEntity entity = httpResponse.getEntity();
            assertNotNull("Response from Web Script is null", entity);
            assertEquals("Incorrect Web Script Response", expectedResponse, EntityUtils.toString(entity));
        } finally {
            httpclient.close();
        }
    }

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

private void testQueryParam(String param) throws ClientProtocolException, IOException {
    HttpClient hc = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(getBaseURL() + "?" + param);
    HttpResponse res = hc.execute(get);/*from   w  w w  . j  a  v  a 2 s  .  co m*/
    assertEquals(200, res.getStatusLine().getStatusCode());

    AssertUtils.assertContains("?" + param, EntityUtils.toString(res.getEntity()));
}