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

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

Introduction

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

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:com.microsoft.azure.hdinsight.spark.common.SparkBatchSubmission.java

/**
 * get all batches spark jobs//from  ww w . j a va  2  s . c  om
 * @param connectUrl : eg http://localhost:8998/batches
 * @return response result
 * @throws IOException
 */
public HttpResponse getAllBatchesSparkJobs(String connectUrl) throws IOException {
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .build();

    HttpGet httpGet = new HttpGet(connectUrl);
    httpGet.addHeader("Content-Type", "application/json");
    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        return StreamUtil.getResultFromHttpResponse(response);
    }
}

From source file:org.wildfly.test.integration.elytron.http.PasswordMechTestBase.java

@Test
public void testInsufficientRole() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role2"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {// w w w  . j  av  a2 s . c  o  m
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_FORBIDDEN, statusCode);
        }
    }
}

From source file:com.byteengine.client.Client.java

public void setProxySettings(String proxyHost, int proxyPort, String proxyUsername, String proxyPass) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    proxyConfig = RequestConfig.custom().setProxy(proxy).build();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPass);
    credsProvider.setCredentials(authScope, creds);

    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java

@Override
public void ping() throws Exception {
    // Setup a client with pre-emptive authentication
    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/* w w w  . jav  a  2s.  c  o  m*/
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // Issue a simple GET against the Info endpoint
        HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info");
        CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
        response.close();
    } finally {
        httpclient.close();
    }
}

From source file:dataServer.StorageRESTClientManager.java

public StorageRESTClientManager() {

    //HttpParams httpParameters = new BasicHttpParams();
    //int timeoutConnection = 5000;
    //HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    //int timeoutSocket = 5000;
    //HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(20);
    connManager.setMaxTotal(40);//from w  w w  .  j  a va 2 s .  c o  m

    client = HttpClients.custom().setConnectionManager(connManager).build();
    requestUrl = null;
    params = null;
    queryString = null;

    //get storage IPs, URLs and Ports from environment variables
    StreamPipes = System.getenv("StreamPipes");
    storageLocation = System.getenv("StorageLocation");
    storagePortReadC = System.getenv("StoragePortReadC");
    storagePortRegistryC = System.getenv("StoragePortRegistryC");

    System.out.println("Environment variables:");
    System.out.println("StreamPipes: " + StreamPipes);
    System.out.println("storageLocation: " + storageLocation);
    System.out.println("storagePortReadC: " + storagePortReadC);
    System.out.println("storagePortRegistryC: " + storagePortRegistryC);
}

From source file:com.tobedevoured.json.SimpleStream.java

/**
 * Stream JSON from url/*from w w w.  java  2 s.  c  om*/
 *
 * @param url String
 * @param timeout int
 * @throws StreamException parser error
 */
public void streamFromUrl(final String url, final int timeout) throws StreamException {
    logger.info("Streaming JSON from {}", url);

    CloseableHttpClient httpclient = HttpClients.custom()
            .setKeepAliveStrategy((response, context) -> timeout * 1000).build();

    HttpGet httpget = new HttpGet(url);

    try {
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                try {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.debug("Streaming line: {}", line);
                        stream(line);
                    }
                } finally {
                    flush();
                    reader.close();
                }
            }
        } finally {
            response.close();
        }

    } catch (Exception e) {
        logger.error("Unexpected error", e);
        throw new StreamException(e);
    }
}

From source file:edu.mit.scratch.ScratchProjectManager.java

@NotWorking
public void toggleCommentsEnabled() throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);//from w  w  w.  j  a va2  s. c  o  m
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final HttpUriRequest update = RequestBuilder.put()
            .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID()
                    + "/toggle-comments/")
            .addHeader("Accept", "*/*")
            .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/")
            .addHeader("Origin", "https://scratch.mit.edu/").addHeader("Accept-Encoding", "gzip, deflate, sdch")
            .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
            .addHeader("X-Requested-With", "XMLHttpRequest")
            .addHeader("Cookie",
                    "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                            + this.session.getCSRFToken())
            .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();
    try {
        resp = httpClient.execute(update);
        System.out.println("current status:" + resp.getStatusLine().getStatusCode());
        if (resp.getStatusLine().getStatusCode() != 200)
            throw new ScratchProjectException();
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);

        System.out.println(result);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
}

From source file:com.kurtraschke.ctatt.gtfsrealtime.services.TrainTrackerDataService.java

public Follow fetchTrain(String runNumber) throws URISyntaxException, IOException, TrainTrackerDataException {
    URIBuilder b = new URIBuilder("http://lapi.transitchicago.com/api/1.0/ttfollow.aspx");
    b.addParameter("key", _trainTrackerKey);
    b.addParameter("runnumber", runNumber);

    CloseableHttpClient client = HttpClients.custom().setConnectionManager(_connectionManager).build();

    HttpGet httpget = new HttpGet(b.build());
    try (CloseableHttpResponse response = client.execute(httpget)) {
        HttpEntity entity = response.getEntity();
        Follow f = _xmlMapper.readValue(entity.getContent(), Follow.class);

        if (f.errorCode != 0) {
            throw new TrainTrackerDataException(f.errorCode, f.errorName);
        }/*from w w  w.  j  a  v  a 2s. c  om*/

        return f;
    }
}

From source file:com.ccc.crest.servlet.auth.CrestAuthCallback.java

private void getVerifyData(Base20ClientInfo clientInfo) throws Exception {
    Properties properties = CoreController.getController().getProperties();
    String verifyUrl = properties.getProperty(CrestController.OauthVerifyUrlKey,
            CrestController.OauthVerifyUrlDefault);
    String userAgent = properties.getProperty(CrestController.UserAgentKey, CrestController.UserAgentDefault);
    //@formatter:off
    CloseableHttpClient httpclient = HttpClients.custom().setUserAgent(userAgent).build();
    //@formatter:on

    String accessToken = ((OAuth2AccessToken) clientInfo.getAccessToken()).getAccessToken();
    HttpGet httpGet = new HttpGet(verifyUrl);
    httpGet.addHeader("Authorization", "Bearer " + accessToken);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {/*from   w  ww. ja v  a 2 s  .  c o m*/
        HttpEntity entity1 = response1.getEntity();
        InputStream is = entity1.getContent();
        String json = IOUtils.toString(is, "UTF-8");
        is.close();
        ((CrestClientInfo) clientInfo).setVerifyData(OauthVerify.getOauthVerifyData(json));
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

From source file:com.digitalpebble.stormcrawler.protocol.httpclient.HttpProtocol.java

@Override
public void configure(final Config conf) {

    super.configure(conf);

    this.maxContent = ConfUtils.getInt(conf, "http.content.limit", -1);

    String userAgent = getAgentString(ConfUtils.getString(conf, "http.agent.name"),
            ConfUtils.getString(conf, "http.agent.version"),
            ConfUtils.getString(conf, "http.agent.description"), ConfUtils.getString(conf, "http.agent.url"),
            ConfUtils.getString(conf, "http.agent.email"));

    builder = HttpClients.custom().setUserAgent(userAgent).setConnectionManager(CONNECTION_MANAGER)
            .setConnectionManagerShared(true).disableRedirectHandling().disableAutomaticRetries();

    String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null);
    int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080);

    boolean useProxy = proxyHost != null && proxyHost.length() > 0;

    // use a proxy?
    if (useProxy) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }//from   w ww . ja  v a  2s  .c o  m

    int timeout = ConfUtils.getInt(conf, "http.timeout", 10000);

    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(timeout);
    requestConfigBuilder.setConnectTimeout(timeout);
    requestConfigBuilder.setConnectionRequestTimeout(timeout);
    requestConfigBuilder.setCookieSpec(CookieSpecs.STANDARD);
    requestConfig = requestConfigBuilder.build();
}