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.fanmei.pay4j.http.WeixinSSLRequestExecutor.java

public WeixinSSLRequestExecutor(WeixinConfig weixinConfig) throws WeixinException {
    InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(weixinConfig.getCertificateFile());
    try {//  w w w .  j a v  a2s  . c om
        String password = weixinConfig.getAccount().getCertificateKey();
        KeyStore keyStore = KeyStore.getInstance(Constants.PKCS12);
        keyStore.load(inputStream, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(Constants.SunX509);
        kmf.init(keyStore, password.toCharArray());
        SSLContext sslContext = SSLContext.getInstance(Constants.TLS);
        sslContext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        throw WeixinException.of("Key load error", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }
    }
}

From source file:org.wso2.apim.billing.clients.DASRestClient.java

/**
 * get instance providing DAS configuration
 *
 * @param url  DAS rest api location/*w w w  .j a v a 2  s  .  c om*/
 * @param user DAS rest api username
 * @param pass DAs rest api password
 */
public DASRestClient(String url, String user, char[] pass) throws MalformedURLException {
    URL dasURL = new URL(url);
    httpClient = HttpClients.custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    this.dasUrl = url;
    this.user = user;
    this.pass = pass;
}

From source file:com.fanmei.pay4j.http.DefaultRequestExecutor.java

public DefaultRequestExecutor() {
    httpClient = HttpClients.custom().build();
}

From source file:io.logspace.system.SolrClientResource.java

@Override
protected void before() throws Throwable {
    this.httpClient = HttpClients.custom().disableAutomaticRetries()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT)
                    .setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build())
            .setDefaultHeaders(Collections.singleton(new BasicHeader("Accept", APPLICATION_JSON.getMimeType())))
            .build();/*w  ww.j a va 2s.com*/
}

From source file:com.github.autermann.wps.streaming.delegate.DelegatingExecutor.java

private CloseableHttpClient createHttpClient() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);/*from w  w w .j av a 2  s  .com*/
    return HttpClients.custom().setConnectionManager(cm).build();
}

From source file:com.kurtraschke.septa.gtfsrealtime.services.TrainViewService.java

public Collection<Train> getTrains() throws URISyntaxException, ClientProtocolException, IOException {
    URIBuilder b = new URIBuilder("http://www3.septa.org/hackathon/TrainView/");

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

    HttpGet httpget = new HttpGet(b.build());
    try (CloseableHttpResponse response = client.execute(httpget);
            InputStream responseInputStream = response.getEntity().getContent();
            Reader responseEntityReader = new InputStreamReader(responseInputStream)) {
        JsonParser parser = new JsonParser();

        JsonArray trainObjects = (JsonArray) parser.parse(responseEntityReader);

        ArrayList<Train> allTrains = new ArrayList<>(trainObjects.size());

        for (JsonElement trainElement : trainObjects) {
            JsonObject trainObject = (JsonObject) trainElement;

            try {
                allTrains.add(new Train(trainObject.get("lat").getAsDouble(),
                        trainObject.get("lon").getAsDouble(), trainObject.get("trainno").getAsString(),
                        trainObject.get("service").getAsString(), trainObject.get("dest").getAsString(),
                        trainObject.get("nextstop").getAsString(), trainObject.get("late").getAsInt(),
                        trainObject.get("SOURCE").getAsString()));
            } catch (Exception e) {
                _log.warn("Exception processing train JSON", e);
                _log.warn(trainObject.toString());
            }/*w ww. j ava2 s  . c  o  m*/
        }
        return allTrains;
    }
}

From source file:com.olacabs.fabric.compute.builder.impl.HttpJarDownloader.java

public HttpJarDownloader() throws Exception {
    FileAttribute<Set<PosixFilePermission>> perms = PosixFilePermissions
            .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x"));
    Path createdPath = Files.createTempDirectory(null, perms);
    this.tmpDirectory = createdPath.toAbsolutePath().toString();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(20);/*from www.ja v a 2s  . com*/

    httpClient = HttpClients.custom().setConnectionManager(cm).build();
}

From source file:eionet.gdem.qa.functions.Json.java

/**
 * Method converts the URL response body into XML format and returns it as String. If the response is not in JSON format, then JsonError object is converted to XML.
 * @param requestUrl Request URL to JSON format content.
 * @return String of XML/* w  w w . j a  v  a 2s  .c  o  m*/
 */
public static String jsonRequest2xmlString(String requestUrl) {
    JsonError error = null;
    String responseString = null;
    String xml = null;
    HttpGet method = null;

    // Create an instance of HttpClient.
    CloseableHttpClient client = HttpClients.custom()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build();
    CloseableHttpResponse response = null;
    try {
        // Create a method instance.
        method = new HttpGet(requestUrl);

        // Provide custom retry handler is necessary
        //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Execute the method.
        response = client.execute(method);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + response.getStatusLine());
            error = new JsonError(statusCode, response.getStatusLine().getReasonPhrase());
        } else {
            // Read the response body.
            HttpEntity entity = response.getEntity();
            byte[] responseBody = IOUtils.toByteArray(entity.getContent());
            responseString = new String(responseBody, "UTF-8");
        }
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal protocol violation.");*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal transport error.");
        e.printStackTrace();
    } catch (Exception e) {
        LOGGER.error("Error: " + e.getMessage());
        e.printStackTrace();
        error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error." + e.getMessage());
    } finally {
        // Release the connection.
        if (method != null) {
            method.releaseConnection();
        }
    }
    if (responseString != null) {
        xml = jsonString2xml(responseString);
    } else if (error != null) {
        xml = jsonString2xml(error);
    } else {
        xml = jsonString2xml(new JsonError());
    }
    return xml;
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public <Result> Result executeGet(String query, final Function<String, Result> responseConverter)
        throws ClientProtocolException, IOException {

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

    HttpUriRequest request = RequestBuilder.get().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).build();
    return client.execute(request, new ResponseHandler<Result>() {

        @Override/*w  w  w  .j  a v  a2 s.com*/
        public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return responseConverter.apply(IOUtils.toString(response.getEntity().getContent()));
        }
    });
}