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.naver.timetable.bo.HttpClientBO.java

public String getHttpBody(String url, String method, List<NameValuePair> param) {
    HttpClient httpClient = null;/*  ww  w.ja v  a 2  s  .  c o  m*/
    HttpResponse httpResponse = null;
    HttpRequestBase httpRequest;

    try {
        if (StringUtils.upperCase(method).equals("POST")) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(param));
        } else {
            httpRequest = new HttpGet(url);
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new DefaultTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
        SSLContext.setDefault(sslContext);

        sslContext.init(null, trustManagers, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        //         httpClient = HttpClientBuilder.create().build();
        httpResponse = httpClient.execute(httpRequest);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
        LOG.error("Client protocol error : ", e);
    } catch (IOException e) {
        LOG.error("IO error : ", e);
    } catch (KeyManagementException e) {
        LOG.error("IO error : ", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("IO error : ", e);
    } finally {
        // ?
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }

    return null;
}

From source file:org.activiti.designer.eclipse.navigator.cloudrepo.ActivitiCloudEditorUtil.java

public static CloseableHttpClient getAuthenticatedClient() {

    // Get settings from preferences
    String url = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_URL);
    String userName = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_USERNAME);
    String password = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_PASSWORD);
    String cookieString = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE);

    Cookie cookie = null;// w  ww .ja v a 2 s  .c o  m
    if (StringUtils.isNotEmpty(cookieString)) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                hexStringToByteArray(cookieString));
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = (BasicClientCookie) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Build session
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    if (cookie == null) {
        try {
            HttpUriRequest login = RequestBuilder.post().setUri(new URI(url + "/rest/app/authentication"))
                    .addParameter("j_username", userName).addParameter("j_password", password)
                    .addParameter("_spring_security_remember_me", "true").build();

            CloseableHttpResponse response = httpClient.execute(login);

            try {
                EntityUtils.consume(response.getEntity());
                List<Cookie> cookies = cookieStore.getCookies();
                if (cookies.isEmpty()) {
                    // nothing to do
                } else {
                    Cookie reponseCookie = cookies.get(0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ObjectOutputStream outputStream = new ObjectOutputStream(os);
                    outputStream.writeObject(reponseCookie);
                    PreferencesUtil.getActivitiDesignerPreferenceStore().setValue(
                            Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE.getPreferenceId(),
                            byteArrayToHexString(os.toByteArray()));
                    InstanceScope.INSTANCE.getNode(ActivitiPlugin.PLUGIN_ID).flush();
                }

            } finally {
                response.close();
            }

        } catch (Exception e) {
            Logger.logError("Error authenticating " + userName, e);
        }

    } else {
        // setting cookie from cache
        cookieStore.addCookie(cookie);
    }

    return httpClient;
}

From source file:com.xx_dev.apn.proxy.test.TestProxyWithHttpClient.java

private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(2000);/*  w w  w. ja  v a 2s  . co  m*/
    cm.setDefaultMaxPerRoute(40);
    cm.setDefaultConnectionConfig(connectionConfig);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm)
            .disableContentCompression().disableCookieManagement().build();

    HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());

    RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true)
            .setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(request);

        Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
        if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
            Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
        }

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseHandler.handleResponse(httpResponse);

        httpResponse.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:com.ibm.nytimes.NewYorkTimes.java

public BestSellerList getList() throws Exception {
    BestSellerList returnedList = new BestSellerList();

    try {//  w ww .  j a  v  a2  s.c  om
        if (listName != null && listDate != null && url != null && apiKey != 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("/svc/books/v2/lists/" + listDate + "/" + listName)
                    .setParameter("api-key", apiKey);
            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 books from the best seller list
                ObjectMapper mapper = new ObjectMapper();
                returnedList = mapper.readValue(rd, BestSellerList.class);
            } else {
                logger.error("could not get list from ny times http code {}",
                        httpResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception e) {
        logger.error("could not get list from ny times {}", e.getMessage());
        throw e;
    }

    return returnedList;
}

From source file:com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpClientProvider.java

@Override
public CloseableHttpClient get() {
    return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
            .setConnectionManager(customConnectionManager()).setDefaultCredentialsProvider(buildCredentials())
            .setDefaultRequestConfig(customRequestConfig()).build();
}

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

public Positions fetchAllTrains(List<String> routes)
        throws MalformedURLException, IOException, TrainTrackerDataException, URISyntaxException {
    URIBuilder b = new URIBuilder("http://lapi.transitchicago.com/api/1.0/ttpositions.aspx");
    b.addParameter("key", _trainTrackerKey);
    b.addParameter("rt", Joiner.on(',').join(routes));

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

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

        if (p.errorCode != 0) {
            throw new TrainTrackerDataException(p.errorCode, p.errorName);
        }//from  ww  w  . j  a  va2s .co m

        return p;
    }
}

From source file:org.hspconsortium.platform.api.smart.LaunchOrchestrationEndpoint.java

public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    HttpPost postRequest = new HttpPost(this.authorizationServerLaunchEndpointURL);
    postRequest.addHeader("Content-Type", "application/json");
    StringEntity entity = null;/*from w  w  w .j  ava  2s.  c  o  m*/
    try {
        entity = new StringEntity(jsonString);
        postRequest.setEntity(entity);

        setAuthorizationHeader(postRequest, apiServerClientId, apiServerClientSecret);
    } catch (UnsupportedEncodingException uee_ex) {
        throw new RuntimeException(uee_ex);
    }

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

    try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(postRequest)) {
        if (closeableHttpResponse.getStatusLine().getStatusCode() != 200) {
            HttpEntity rEntity = closeableHttpResponse.getEntity();
            String responseString = EntityUtils.toString(rEntity, "UTF-8");
            throw new RuntimeException(String.format(
                    "There was a problem with the registration the Launch Context.\n"
                            + "Response Status : %s .\nResponse Detail :%s.",
                    closeableHttpResponse.getStatusLine(), responseString));
        }
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getWriter().write(EntityUtils.toString(closeableHttpResponse.getEntity()));
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:org.fcrepo.camel.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient/*from w w  w .j a  va  2 s.  co m*/
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createDefault();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}

From source file:org.fcrepo.client.FcrepoHttpClientBuilder.java

/**
 *  Build an HttpClient//from   w  w  w  . j a v a2 s.  c  om
 *
 *  @return an HttpClient
 */
public CloseableHttpClient build() {

    if (isBlank(username) || isBlank(password)) {
        return HttpClients.createSystem();
    } else {
        LOGGER.debug("Accessing fcrepo with user credentials");

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope scope = null;

        if (isBlank(host)) {
            scope = new AuthScope(AuthScope.ANY);
        } else {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).useSystemProperties().build();
    }
}

From source file:name.martingeisse.trading_game.platform.fakecdn.FakeCdn.java

/**
 *
 *///w  w  w  .  ja  v a 2 s . c  o  m
private HttpResponse fetchResponse(String url) throws IOException {

    // TODO inject HttpClient

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCookieStore(new NullCookieStore()).build();
    for (int i = 0; i < 10; i++) {
        HttpUriRequest request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < 300 || statusCode >= 400) {
            return response;
        }
        url = response.getFirstHeader("Location").getValue();
        if (url == null) {
            throw new IOException("redirect without location header");
        }
    }
    throw new IOException("too many redirects");
}