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.abc.turkey.service.unfreeze.UnfreezeProxy.java

public UnfreezeProxy() {
    logger.info("create proxy==");
    smsService = SpringContextUtil.getBean(SmsService.class);
    ArrayList<Header> headers = new ArrayList<Header>();
    // headers.add(new BasicHeader("Referer", referer));
    headers.add(new BasicHeader("User-Agent", agent));
    // forbid redirect
    RedirectStrategy redirectStrategy = new RedirectStrategy() {

        @Override//from w  w w . jav  a 2s  . c o  m
        public boolean isRedirected(HttpRequest arg0, HttpResponse arg1, HttpContext arg2)
                throws ProtocolException {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public HttpUriRequest getRedirect(HttpRequest arg0, HttpResponse arg1, HttpContext arg2)
                throws ProtocolException {
            // TODO Auto-generated method stub
            return null;
        }
    };
    httpclient = HttpClients.custom().setDefaultHeaders(headers).setRedirectStrategy(redirectStrategy).build();
}

From source file:synapticloop.getcookie.api.GetCookieApiClient.java

public GetCookieApiClient() {
    HttpClientBuilder httpBuilder = HttpClients.custom();
    httpBuilder.setUserAgent(Constants.USER_AGENT);
    this.httpclient = httpBuilder.build();
}

From source file:io.fabric8.maven.docker.access.hc.http.HttpClientBuilder.java

public CloseableHttpClient buildPooledClient() throws IOException {
    org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom();
    HttpClientConnectionManager manager = getPooledConnectionFactory(certPath, maxConnections);
    builder.setConnectionManager(manager);
    // TODO: For push-redirects working for 301, the redirect strategy should be relaxed (see #351)
    // However not sure whether we should do it right now and whether this is correct, since normally
    // a 301 should only occur when the image name is invalid (e.g. containing "//" in which case a redirect
    // happens to the URL with a single "/")
    // builder.setRedirectStrategy(new LaxRedirectStrategy());

    // TODO: Tune client if needed (e.g. add pooling factoring .....
    // But I think, that's not really required.

    return builder.build();
}

From source file:com.ibm.subway.NewYorkSubway.java

public StationList getTrainList(String stationId, Locale locale, boolean translate) throws Exception {
    logger.debug("Station {}", stationId);
    StationList returnedList = new StationList();
    WatsonTranslate watson = new WatsonTranslate(locale);

    try {/*from   w w w.  java2  s  . c om*/
        if (stationId != null) {
            RequestConfig config = RequestConfig.custom().setSocketTimeout(10 * 1000)
                    .setConnectTimeout(10 * 1000).build();
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();

            URIBuilder builder = new URIBuilder();
            builder.setScheme("http").setHost(url).setPath("/by-id/" + stationId);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "text/plain");

            HttpResponse httpResponse = httpclient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

                // Read all the trains from the list
                ObjectMapper mapper = new ObjectMapper();
                returnedList = mapper.readValue(rd, StationList.class);

                // Set the direction of the trains
                ArrayList<Station> stations = returnedList.getStationList();
                for (Station station : stations) {
                    String northString = "North";
                    String southString = "South";

                    if (translate) {
                        northString = watson.translate(northString);
                        southString = watson.translate(southString);
                    }

                    ArrayList<Train> north = station.getNorthTrains();
                    for (Train train : north) {
                        train.setDirection(northString);
                    }
                    ArrayList<Train> south = station.getSouthTrains();
                    for (Train train : south) {
                        train.setDirection(southString);
                    }
                }
            } else {
                logger.error("could not get list from MTA http code {}",
                        httpResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception e) {
        logger.error("could not get list from MTA {}", e.getMessage());
        throw e;
    }

    return returnedList;
}

From source file:org.geosdi.geoplatform.gui.GetMapUrlTest.java

@Test
public void getMapUrlTest() throws Exception {
    CloseableHttpClient client = HttpClients.custom().build();
    String url = "http://150.145.141.92/geoserver/wms?service=WMS&amp;version=1.1.0&amp;request=GetMap&amp;layers=topp:states&amp;styles=&amp;bbox=1724753.45766073,5099790.02370763,1725687.17361712,5100561.22571727&amp;width=512&amp;height=422&amp;srs=EPSG:3003&amp;format=image/png";
    HttpGet get = new HttpGet(url.replaceAll("&amp;", "&"));
    CloseableHttpResponse response = client.execute(get);

    logger.info("###############################{}", response.getEntity().getContentType().getValue());
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.Exports.java

@Override
public void register(Registry registry) {
    registry.add(new Builder.Factory<ExecutorService>() {
        @Override//from w  w  w .j  ava2  s  .  c  o m
        public <S> ExecutorService create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            return Executors.newCachedThreadPool();
        }
    });

    registry.add(new Builder.Factory<ApacheConfigSettings>() {
        @Override
        public <S> ApacheConfigSettings create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            if (!ManagementConfiguration.isPlayback()
                    && properties.containsKey(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS)) {
                CloudCredentials cloudCredentials = (CloudCredentials) properties
                        .get(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS);
                cloudCredentials.applyConfig(profile, properties);
            }

            return new ApacheConfigSettings(profile, properties);
        }
    });

    registry.add(new Builder.Factory<HttpClientBuilder>() {
        @Override
        public <S> HttpClientBuilder create(String profile, Class<S> service, Builder builder,
                Map<String, Object> properties) {

            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            ApacheConfigSettings settings = builder.build(profile, service, ApacheConfigSettings.class,
                    properties);

            return settings.applyConfig(httpClientBuilder);
        }
    });
}

From source file:org.docx4j.services.client.ConverterHttp.java

/**
 * Convert File fromFormat to toFormat, streaming result to OutputStream os.
 * /*from   w w  w. j  av a2  s .co m*/
 * fromFormat supported: DOC, DOCX
 * 
 * toFormat supported: PDF
 * 
 * @param f
 * @param fromFormat
 * @param toFormat
 * @param os
 * @throws IOException
 * @throws ConversionException
 */
public void convert(File f, Format fromFormat, Format toFormat, OutputStream os)
        throws IOException, ConversionException {

    checkParameters(fromFormat, toFormat);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(new MyRetryHandler()).build();

    try {
        HttpPost httppost = getUrlForFormat(toFormat);

        HttpEntity reqEntity = new FileEntity(f, map(fromFormat));

        httppost.setEntity(reqEntity);

        execute(httpclient, httppost, os);
        log.debug("..done");
    } finally {
        httpclient.close();
    }

}

From source file:co.cask.cdap.client.rest.RestClient.java

public RestClient(RestClientConnectionConfig config, HttpClientConnectionManager connectionManager) {
    this.config = config;
    this.baseUrl = URI.create(String.format("%s://%s:%d", config.isSSL() ? HTTPS_PROTOCOL : HTTP_PROTOCOL,
            config.getHost(), config.getPort()));
    this.version = config.getVersion();
    this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
}

From source file:org.smartloli.kafka.eagle.common.util.TestHttpClientUtils.java

/**
 * send & get response result./*www  .  jav a2 s . c  o m*/
 * 
 * @param httpPost
 */
private static void executeAndGetResponse(HttpPost httpPost) {
    CloseableHttpClient httpClient = HttpClients.custom().build();
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        LOG.info("dingding server result:" + result);
        httpClient.close();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.appdirect.sdk.feature.OrderValidationIsWiredUpIntegrationTest.java

private CloseableHttpClient createHttpClient() {
    return HttpClients.custom().setUserAgent("Apache-HttpClient/4.3.6 (java 1.5)")
            .setDefaultHeaders(asList(new BasicHeader(HttpHeaders.ACCEPT, "application/json, application/xml"),
                    new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate"),
                    new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")))
            .disableRedirectHandling().build();
}