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.respam.comniq.models.OMDBParser.java

public void requestOMDB(String movie, String year) {
    String imageURL;/*w  ww  . j  a  va  2 s.  co m*/

    // Location for downloading and storing thumbnails
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output"
            + File.separator + "thumbnails";
    File userOutDir = new File(path);

    // Create Thumbnails directory if not present
    if (userOutDir.mkdirs()) {
        System.out.println(userOutDir + " was created");
    }

    // Connect to OMDB API and fetch details
    try {
        // Proxy details
        HttpHost proxy = new HttpHost("web-proxy.in.hpecorp.net", 8080, "http");

        //            HttpClient client = HttpClientBuilder.create().build();

        // Start of proxy client
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build();
        // End of proxy client

        String uri = "http://www.omdbapi.com/?t=" + URLEncoder.encode(movie) + "&y=" + year;
        uri = uri.replace(" ", "%20");
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        String json = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(json);

        // Excluding Non Movies
        if (null != jsonObject.get("Title")) {
            movieInfo.add(jsonObject);

            // Download the thumbnails if Poster URL present
            if (null != jsonObject.get("Poster")) {
                imageURL = ((String) jsonObject.get("Poster"));
                System.out.println(imageURL);
                URL thumbnail = new URL(imageURL);
                ReadableByteChannel rbc = Channels.newChannel(thumbnail.openStream());
                FileOutputStream fos = new FileOutputStream(
                        path + File.separator + jsonObject.get("Title") + ".jpg");
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
        }

    } catch (ParseException | IOException | UnsupportedOperationException e) {
        e.printStackTrace();
    }
}

From source file:org.ops4j.pax.web.itest.VirtualHostsTest.java

@Test
public void shouldFindResourceOnVirtualHost() throws Exception {
    assertThat(servletContext.getContextPath(), is("/cm-static"));

    String path = String.format("http://localhost:%d/cm-static/hello", getHttpPort());
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpClient client = HttpClients.custom().build();
    HttpGet httpGet = new HttpGet(path);
    httpGet.setHeader("Host", "alias1");
    HttpResponse response = client.execute(httpGet, context);

    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, is(200));//  w w w  .jav a2s  . co m

    String text = EntityUtils.toString(response.getEntity());
    assertThat(text, containsString("Hello from Pax Web!"));
}

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

public void clearMessages() throws ScratchUserException {
    try {/* ww w . j av  a2 s. c  o  m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/messages/ajax/messages-clear/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").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();

        httpClient.execute(update);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }
}

From source file:madgik.exareme.worker.art.container.dataTrasferMgr.DataTransferMgr.java

public DataTransferMgr(int port) throws RemoteException {
    this.transferIdToRegIds = new HashMap<>();
    this.port = port;
    log.debug("\t DataTranfer starting on port: " + port + "...");

    dataTransfer = ContainerDataTransferGatewayFactory.createDataTransferServer("0.0.0.0", port);
    dataTransfer.start();/*w  w  w .j  a v a 2s.  com*/
    this.nextDtOpId = 0;
    this.nextDtRegId = 0;
    this.operatorNameToTransferID = new HashMap<>();
    this.transferIdToAoimpl = new HashMap<>();
    this.transferIdToRegIds = new HashMap<>();
    this.IPtoDTId = new HashMap<>();
    this.RegIDToFilename = new HashMap<>();
    this.RegIDToTableFile = new HashMap<>();
    this.RedIdToTransferId = new HashMap<>();
    this.transferIDToNumOfDts = new HashMap<>();

    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();
    log.debug("Http client created.");

}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java

/**
 * EGet the authenfication by executing the defined requests sequence.
 *
 * @throws IOException/*from   ww  w.ja  v a 2 s  .com*/
 * @throws ClientProtocolException
 */
public ExitStatus authentificate() throws ClientProtocolException, IOException {
    authCookie = null;

    if (firstRequest != null) {

        final CookieStore cookieStore = new BasicCookieStore();
        client = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setRedirectStrategy(new LaxRedirectStrategy()).useSystemProperties().build();

        lastResponse = firstRequest.executeSequence(client);

        final List<Cookie> cookies = cookieStore.getCookies();
        final StringBuilder strBuff = new StringBuilder();
        for (final Cookie cookie : cookies) {
            strBuff.append(cookie.getName());
            strBuff.append("=");
            strBuff.append(cookie.getValue());
            strBuff.append(";");
        }

        authCookie = strBuff.toString();
    }

    return ExitStatus.COMPLETED;
}

From source file:org.apache.heron.uploader.http.HttpUploader.java

@Override
public URI uploadPackage() throws UploaderException {
    try (CloseableHttpClient httpclient = HttpClients.custom().build()) {
        return uploadPackageAndGetURI(httpclient);
    } catch (IOException | URISyntaxException e) {
        String msg = "Error uploading package to location: " + this.topologyPackageLocation;
        LOG.log(Level.SEVERE, msg, e);
        throw new UploaderException(msg, e);
    }/*from   w  w  w. ja  va 2  s  .com*/
}

From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java

@Test
public void testServer_auth() {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(USER, PASSWORD);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    }/*from w  w  w. jav a  2  s . co m*/
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testHttpRedirect() throws IOException, InterruptedException, ExecutionException {
    final HttpGet httpGet = new HttpGet("http://localhost:8080/redirect");
    try (final CloseableHttpClient client = HttpClients.custom().disableRedirectHandling()
            .setDefaultRequestConfig(requestConfig).build()) {
        final CloseableHttpResponse res = client.execute(httpGet);
        final String s = EntityUtils.toString(res.getEntity());
        System.out.println(s);//from   w ww.java  2  s  .  c om
        assertEquals(302, res.getStatusLine().getStatusCode());
        assertTrue(res.getFirstHeader("Location").getValue().endsWith("/foo"));
    }
}

From source file:gobblin.compaction.audit.PinotAuditCountHttpClient.java

/**
 * Constructor//  w  w w . j ava 2 s  .  c  om
 */
public PinotAuditCountHttpClient(State state) {
    int maxTotal = state.getPropAsInt(CONNECTION_MAX_TOTAL, DEFAULT_CONNECTION_MAX_TOTAL);
    int maxPerRoute = state.getPropAsInt(MAX_PER_ROUTE, DEFAULT_MAX_PER_ROUTE);

    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotal);
    cm.setDefaultMaxPerRoute(maxPerRoute);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();

    String host = state.getProp(TARGET_HOST);
    int port = state.getPropAsInt(TARGET_PORT);
    targetUrl = host + ":" + port + "/pql?pql=";
}

From source file:com.cloud.agent.direct.download.HttpsDirectTemplateDownloader.java

public HttpsDirectTemplateDownloader(String url, Long templateId, String destPoolPath, String checksum,
        Map<String, String> headers) {
    super(url, templateId, destPoolPath, checksum, headers);
    SSLContext sslcontext = null;
    try {/*from   w  w  w  .java  2 s .c o m*/
        sslcontext = getSSLContext();
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | KeyManagementException e) {
        throw new CloudRuntimeException("Failure getting SSL context for HTTPS downloader: " + e.getMessage());
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
            .setSocketTimeout(5000).build();
    httpsClient = HttpClients.custom().setSSLSocketFactory(factory).setDefaultRequestConfig(config).build();
    createUriRequest(url, headers);
}