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:org.mobicents.servlet.restcomm.http.CustomHttpClientBuilder.java

private static HttpClient buildAllowallClient(RequestConfig requestConfig) {
    HttpConnectorList httpConnectorList = UriUtils.getHttpConnectorList();
    HttpClient httpClient = null;//from   w w  w  .j  a v a2  s .c om
    //Enable SSL only if we have HTTPS connector
    List<HttpConnector> connectors = httpConnectorList.getConnectors();
    Iterator<HttpConnector> iterator = connectors.iterator();
    while (iterator.hasNext()) {
        HttpConnector connector = iterator.next();
        if (connector.isSecure()) {
            SSLConnectionSocketFactory sslsf;
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                sslsf = new SSLConnectionSocketFactory(builder.build());
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                        .setSSLSocketFactory(sslsf).build();
            } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
                throw new RuntimeException("Error creating HttpClient", e);
            }
            break;
        }
    }
    if (httpClient == null) {
        httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    }

    return httpClient;
}

From source file:org.jwebsocket.sso.HTTPSupport.java

/**
 *
 * @param aURL/*  www. j av  a2  s .c o m*/
 * @param aMethod
 * @param aHeaders
 * @param aPostBody
 * @param aTimeout
 * @return
 */
public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody,
        long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: "
                + aHeaders + ", Body: "
                + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'"
                        : "[null]"));
    }
    String lResponse = "{\"code\": -1, \"msg\": \"undefined\"";
    try {
        KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        lTrustStore.load(null, null);
        // Trust own CA and all self-signed certs
        SSLContext lSSLContext = SSLContexts.custom()
                .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build();
        HttpUriRequest lRequest;
        if ("POST".equals(aMethod)) {
            lRequest = new HttpPost(aURL);
            ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8")));
        } else {
            lRequest = new HttpGet(aURL);
        }
        for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) {
            lRequest.setHeader(lEntry.getKey(), lEntry.getValue());
        }

        // System.out.println("Executing request " + lRequest.getRequestLine());
        // Create a custom response handler
        ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse lResponse)
                    throws ClientProtocolException, IOException {
                int lStatus = lResponse.getStatusLine().getStatusCode();
                HttpEntity lEntity = lResponse.getEntity();
                return lEntity != null ? EntityUtils.toString(lEntity) : null;

                //               if (lStatus >= 200 && lStatus < 300) {
                //                  HttpEntity entity = lResponse.getEntity();
                //                  return entity != null ? EntityUtils.toString(entity) : null;
                //               } else {
                //                  throw new ClientProtocolException("Unexpected response status: " + lStatus);
                //               }
            }

        };
        long lStartedAt = System.currentTimeMillis();
        lResponse = lHTTPClient.execute(lRequest, lResponseHandler);
        if (mLog.isDebugEnabled()) {
            mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '"
                    + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lResponse;
    } catch (Exception lEx) {
        String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: "
                + lEx.getMessage() + "\"}";
        mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg);
        lResponse = lMsg;
        return lResponse;
    }
}

From source file:org.zalando.stups.tokens.CloseableTokenVerifier.java

public CloseableTokenVerifier(URI tokenInfoUri, HttpConfig httpConfig, MetricsListener metricsListener) {
    this.tokenInfoUri = tokenInfoUri;
    this.metricsListener = metricsListener;

    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    client = HttpClients.custom().setUserAgent(new UserAgent().get()).useSystemProperties().build();

    host = new HttpHost(tokenInfoUri.getHost(), tokenInfoUri.getPort(), tokenInfoUri.getScheme());
}

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

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

    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();

        JsonObject root = (JsonObject) parser.parse(responseEntityReader);

        JsonArray routes = (JsonArray) Iterables.getOnlyElement(root.entrySet()).getValue();

        List<Bus> allBuses = new ArrayList<>();

        for (JsonElement routeElement : routes) {
            JsonArray buses = ((JsonArray) (Iterables.getOnlyElement(((JsonObject) routeElement).entrySet())
                    .getValue()));/*from   w w w . j  av  a2  s  .  c o m*/

            for (JsonElement busElement : buses) {
                JsonObject busObject = (JsonObject) busElement;

                try {
                    allBuses.add(new Bus(busObject.get("lat").getAsDouble(), busObject.get("lng").getAsDouble(),
                            busObject.get("label").getAsString(), busObject.get("VehicleID").getAsString(),
                            busObject.get("BlockID").getAsString(), busObject.get("Direction").getAsString(),
                            (!(busObject.get("destination") instanceof JsonNull))
                                    ? busObject.get("destination").getAsString()
                                    : null,
                            busObject.get("Offset").getAsInt()));
                } catch (Exception e) {
                    _log.warn("Exception processing bus JSON", e);
                    _log.warn(busObject.toString());
                }
            }
        }
        return allBuses;
    }
}

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

@Test
public void testServer_2() {
    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("USER", "PASSWORD"));
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();

    // No auth set - should work.
    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestServer.urlDataset(), "*/*")) {
    } catch (HttpException ex) {
        Assert.assertTrue(ex.getResponseCode() == HttpSC.FORBIDDEN_403
                || ex.getResponseCode() == HttpSC.UNAUTHORIZED_401);
        throw ex;
    }//from   ww w .  j a  v a  2s.  c  o m
}

From source file:com.match_tracker.twitter.TwitterSearch.java

public TwitterSearch(URL twitterSearchAuthUrl) throws MalformedURLException {
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
    Unirest.setHttpClient(httpclient);//from  w  w  w. j av  a 2s .  co m

    this.twitterSearchURL = new URL(twitterSearchAuthUrl, SEARCH_API);
}

From source file:com.github.restdriver.clientdriver.integration.SecureClientDriverTest.java

@Test
public void testConnectionSucceedsWithGivenTrustMaterial() throws Exception {

    // Arrange// w w w. j  a  va  2  s  .c o m
    KeyStore keyStore = getKeystore();
    SecureClientDriver driver = new SecureClientDriver(
            new DefaultClientDriverJettyHandler(new DefaultRequestMatcher()), 1111, keyStore, "password",
            "certificate");
    driver.addExpectation(onRequestTo("/test"), giveEmptyResponse());

    // set the test certificate as trusted
    SSLContext context = SSLContexts.custom().loadTrustMaterial(keyStore, TrustSelfSignedStrategy.INSTANCE)
            .build();
    HttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setSSLContext(context).build();
    HttpGet getter = new HttpGet(driver.getBaseUrl() + "/test");

    // Act
    HttpResponse response = client.execute(getter);

    // Assert
    assertEquals(204, response.getStatusLine().getStatusCode());
    driver.verify();
}

From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    /**// w w w .j  ava 2s. co m
     * ?PKCS12? ?-- API 
     */
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    /**
     * ?
     */
    //ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ "");
    //      FileInputStream instream = new FileInputStream(new File("D:/Program Files/MyEclipse 6.5/workspace/weidian/WebRoot/cer/apiclient_cert.p12"));//P12
    FileInputStream instream = new FileInputStream(
            ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + WxpayConfig.cert_path));
    try {
        /**
         * ?
         * MCHID
         * */
        keyStore.load(instream, WxpayConfig.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxpayConfig.mch_id.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??

        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:net.fischboeck.discogs.DiscogsClient.java

private void init() {
    HttpClientBuilder builder = HttpClients.custom();
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build();

    this.httpClient = builder.setDefaultHeaders(this.getDefaultHeaders()).setDefaultRequestConfig(requestConfig)
            .build();//from   www  .  j  av  a  2 s  .com

    this.mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}