Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:com.tremolosecurity.scalejs.register.ws.ScaleRegister.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError",
            "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/register/config")) {
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(scaleConfig).trim());

    } else if (request.getRequestURI().endsWith("/register/submit")) {
        ScaleError errors = new ScaleError();
        String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
        NewUserRequest newUser = gson.fromJson(json, NewUserRequest.class);

        if (scaleConfig.isRequireReCaptcha()) {
            if (newUser.getReCaptchaCode() == null || newUser.getReCaptchaCode().isEmpty()) {
                errors.getErrors().add("Please verify you are not a robot");
            } else {
                BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                        GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
                RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
                CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(rc).build();
                HttpPost httppost = new HttpPost("https://www.google.com/recaptcha/api/siteverify");

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair("secret", scaleConfig.getRcSecretKey()));
                formparams.add(new BasicNameValuePair("response", newUser.getReCaptchaCode()));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

                httppost.setEntity(entity);

                CloseableHttpResponse resp = http.execute(httppost);

                ReCaptchaResponse res = gson.fromJson(EntityUtils.toString(resp.getEntity()),
                        ReCaptchaResponse.class);

                if (!res.isSuccess()) {
                    errors.getErrors().add("Human validation failed");
                }//  ww  w  .j  a  v  a 2s.c  om

                http.close();
                bhcm.close();

            }
        }

        if (scaleConfig.isRequireTermsAndConditions() && !newUser.isCheckedTermsAndConditions()) {
            errors.getErrors().add("You must accept the terms and conditions to register");
        }

        if (this.scaleConfig.isRequireReason()
                && (newUser.getReason() == null || newUser.getReason().isEmpty())) {
            errors.getErrors().add("Reason is required");
        }

        if (this.scaleConfig.isPreSetPassword()) {
            if (newUser.getPassword() == null || newUser.getPassword().isEmpty()) {
                errors.getErrors().add("Password is required");
            } else if (!newUser.getPassword().equals(newUser.getPassword2())) {
                errors.getErrors().add("Passwords must match");
            }
        }

        for (String attributeName : this.scaleConfig.getAttributes().keySet()) {
            String value = newUser.getAttributes().get(attributeName);

            if (this.scaleConfig.getAttributes().get(attributeName) == null) {
                errors.getErrors().add("Invalid attribute : '" + attributeName + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isReadOnly()) {
                errors.getErrors().add("Attribute is read only : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isRequired()
                    && (value == null || value.length() == 0)) {
                errors.getErrors().add("Attribute is required : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMinChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMinChars() < value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at least "
                        + this.scaleConfig.getAttributes().get(attributeName).getMinChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at most "
                        + this.scaleConfig.getAttributes().get(attributeName).getMaxChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getType().equalsIgnoreCase("list")) {
                boolean found = false;
                for (NVP nvp : this.scaleConfig.getAttributes().get(attributeName).getValues()) {
                    if (nvp.getValue().equalsIgnoreCase(value)) {
                        found = true;
                    }
                }

                if (!found) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " has an invalid value");
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).getPattern() != null) {
                boolean ok = true;
                try {
                    Matcher m = this.scaleConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                    if (m == null || !m.matches()) {
                        ok = false;
                    }
                } catch (Exception e) {
                    ok = false;
                }

                if (!ok) {
                    errors.getErrors().add("Attribute value not valid : '"
                            + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "' - "
                            + this.scaleConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).isUnique()) {
                String filter = equal(attributeName, value).toString();

                LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(
                        GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, filter,
                        new ArrayList<String>());
                if (res.hasMore()) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " is not available");
                }
                while (res.hasMore())
                    res.next();
            }
        }

        WFCall wfcall = null;
        String wfName = this.scaleConfig.getWorkflowName();
        if (errors.getErrors().isEmpty()) {
            if (scaleConfig.isUseCustomSubmission()) {

                AuthInfo userData = ((AuthController) request.getSession()
                        .getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();

                wfName = cru.createTremoloUser(newUser, errors.getErrors(), userData);
            }
        }

        if (errors.getErrors().isEmpty()) {
            TremoloUser user = new TremoloUser();

            AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
                    .getAuthInfo();

            if (this.scaleConfig.isSubmitLoggedInUser()) {
                user.setUid(
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0));
                user.getAttributes().add(new Attribute(this.scaleConfig.getUidAttributeName(),
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0)));
            } else {
                user.setUid(newUser.getAttributes().get(this.scaleConfig.getUidAttributeName()));
            }

            for (String attrName : newUser.getAttributes().keySet()) {
                user.getAttributes().add(new Attribute(attrName, newUser.getAttributes().get(attrName)));
            }

            if (this.scaleConfig.isPreSetPassword()) {
                user.setUserPassword(newUser.getPassword());

            }

            wfcall = new WFCall();
            wfcall.setUidAttributeName(this.scaleConfig.getUidAttributeName());
            wfcall.setReason(newUser.getReason());
            wfcall.setName(wfName);
            wfcall.setUser(user);

            HashMap<String, Object> params = new HashMap<String, Object>();
            wfcall.setRequestParams(params);

            if (userData.getAuthLevel() != 0 && !this.scaleConfig.isSubmitLoggedInUser()) {
                wfcall.setRequestor(
                        userData.getAttribs()
                                .get(GlobalEntries.getGlobalEntries().getConfigManager().getCfg()
                                        .getProvisioning().getApprovalDB().getUserIdAttribute())
                                .getValues().get(0));
                wfcall.getRequestParams().put(Approval.SEND_NOTIFICATION, "false");
                wfcall.getRequestParams().put(Approval.REASON, newUser.getReason());
                wfcall.getRequestParams().put(Approval.IMMEDIATE_ACTION, "true");
            }

            ExecuteWorkflow exec = new ExecuteWorkflow();

            try {
                exec.execute(wfcall, GlobalEntries.getGlobalEntries().getConfigManager());
            } catch (Exception e) {
                throw new ProvisioningException("Could not complete registration", e);
            }

            SubmitResponse res = new SubmitResponse();
            res.setAddNewUsers(userData.getAuthLevel() != 0);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(res));
            response.getWriter().flush();

        } else {
            response.setStatus(500);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(errors).trim());
            response.getWriter().flush();
        }

    } else {
        response.setStatus(500);
        ScaleJSUtils.addCacheHeaders(response);
        ScaleError error = new ScaleError();
        error.getErrors().add("Operation not supported");
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    }

}

From source file:com.cht.imserver.push.TLPushNotification.java

public static PNResult pushMessage_iOS(String token, String message, String lockey, String locargs,
        String sound, int badge, String licenseKey, PNServerType type, String proxy, int port)
        throws IOException, UnsupportedEncodingException, ClientProtocolException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost httpproxy = null;/*  w w w .  j a v a  2s. c o m*/
    String serverURL = null;
    PNResult result = null;
    if (type == PNServerType.ios_dev) {
        serverURL = deviOSHost;
    } else if (type == PNServerType.ios_official) {
        serverURL = officeialiOSHost;
    }
    String jsontoken = "{\"iosTokens\":[{\"token\":\"" + token + "\",\"badge\" : " + String.valueOf(badge)
            + "}]}";
    String jsonmessage = null;
    if (lockey == null || "".equals(lockey)) {
        jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\"}";
    } else {
        jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\",\"loc-key\":\"" + lockey
                + "\",\"loc-args\":" + locargs + "}";
    }
    //System.out.println("iosdata=" + jsonmessage);
    //System.out.println("iostoken=" + jsontoken);

    //logger.info("jsonmessage:" + jsonmessage + ", jsontoken:" + jsontoken + ", licenseKey:" + licenseKey );
    logger.info("jsonmessage:" + jsonmessage + ", licenseKey:" + licenseKey);

    try {
        HttpPost httpPost = new HttpPost(serverURL);
        if (proxy != null) {
            httpproxy = new HttpHost(proxy, port);
            RequestConfig config = RequestConfig.custom().setProxy(httpproxy).build();
            httpPost.setConfig(config);
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("iosdata", jsonmessage));
        nvps.add(new BasicNameValuePair("iostoken", jsontoken));
        nvps.add(new BasicNameValuePair("licensekey", licenseKey));
        nvps.add(new BasicNameValuePair("appname", appname));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        //System.out.println(EntityUtils.toString(httpPost.getEntity()) );
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        Gson mGson = new Gson();
        try {
            //System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            //System.out.println(EntityUtils.toString(entity2));
            result = mGson.fromJson(EntityUtils.toString(entity2), PNResult.class);

            EntityUtils.consume(entity2);

        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
    return result;

}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Calls a http node of JEM to submit a job.
 * /*from ww w  .ja va  2  s. c o m*/
 * @param user user to authenticate
 * @param password password to authenticate
 * @param url http URL to call
 * @param prejob job instance to submit
 * @return job id
 * @throws SubmitException if errors occur
 */
public static String submit(String user, String password, String url, PreJob prejob) throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    boolean loggedIn = false;
    try {
        httpclient = createHttpClient(url);
        // prepares the entity to send via HTTP
        XStream streamer = new XStream();
        String content = streamer.toXML(prejob);

        login(user, password, url, httpclient);
        loggedIn = true;
        // concats URL with query string
        String completeUrl = url + HttpUtil.SUBMIT_QUERY_STRING;
        StringEntity entity = new StringEntity(content,
                ContentType.create("text/xml", CharSet.DEFAULT_CHARSET_NAME));

        // prepares POST request and basic response handler
        HttpPost httppost = new HttpPost(completeUrl);
        httppost.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httppost, responseHandler);
        return responseBody.trim();
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } finally {
        if (loggedIn) {
            try {
                logout(url, httpclient);
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url, String[] replaceParams, String[] params) {
    String result;//from w w w  .  java 2s. com
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        if (replaceParams.length > 0) {
            for (int i = 0; i < replaceParams.length; i++) {
                Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.FINE, replaceParams[i],
                        params[i]);
                url = url.replaceAll(replaceParams[i], params[i]);
            }
        }

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpGet getMethod = new HttpGet(url);

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getExceptionMessage() + status);
            }
        };

        result = client.execute(getMethod, responseHandler);
        client.close();

    } catch (SocketTimeoutException ex) {
        result = hcp.getTimeoutMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        result = hcp.getFailMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

private Integer doRequest(final HttpRequestBase request)
        throws ClientProtocolException, IOException, InterruptedException {
    final CountDownLatch waitForCompletion = new CountDownLatch(1);

    final URI uri = request.getURI();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin"));
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//from   w w w  . j  a  v a  2  s  .c o m

    final CloseableHttpClient client = HttpClients.createDefault();

    final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() {
        @Override
        public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            try {
                final int status = response.getStatusLine().getStatusCode();
                // 400 because we return that if you try to delete something that is already deleted
                // 404 because it's OK if it's already not there
                if (status >= 200 && status < 300 || status == 400 || status == 404) {
                    EntityUtils.consume(response.getEntity());
                    return status;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            } finally {
                waitForCompletion.countDown();
            }
        }
    };

    final Integer status = client.execute(targetHost, request, responseHandler, context);

    waitForCompletion.await();
    client.close();
    return status;
}

From source file:com.smartling.api.sdk.util.HttpUtils.java

/**
 * Method for executing http calls and retrieving string response.
 * @param httpRequest request for execute
 * @param proxyConfiguration proxy configuration, if it is set to {@code NULL} proxy settings will be setup from system properties. Otherwise switched off.
 * @return {@link StringResponse} the contents of the requested file along with the encoding of the file.
 * @throws com.smartling.api.sdk.exceptions.SmartlingApiException if an exception has occurred or non success is returned from the Smartling Translation API.
 *//*from   ww  w  . j av  a  2s. c om*/
public StringResponse executeHttpCall(final HttpRequestBase httpRequest,
        final ProxyConfiguration proxyConfiguration) throws SmartlingApiException {
    CloseableHttpClient httpClient = null;
    try {
        requestId.remove();
        responseDetails.remove();

        ProxyConfiguration newProxyConfiguration = mergeSystemProxyConfiguration(proxyConfiguration);

        logProxyConfiguration(newProxyConfiguration);

        httpClient = httpProxyUtils.getHttpClient(newProxyConfiguration);

        RequestConfig proxyRequestConfig = httpProxyUtils.getProxyRequestConfig(httpRequest,
                newProxyConfiguration);

        if (proxyRequestConfig != null) {
            httpRequest.setConfig(proxyRequestConfig);
        }
        addUserAgentHeader(httpRequest);
        final HttpResponse response = httpClient.execute(httpRequest);

        final String charset = EntityUtils.getContentCharSet(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();

        Header header = response.getFirstHeader(X_SL_REQUEST_ID);
        if (header != null) {
            requestId.set(header.getValue());
        }

        ResponseDetails details = new ResponseDetails(statusCode, response.getAllHeaders());
        responseDetails.set(details);

        return inputStreamToString(response.getEntity().getContent(), charset, statusCode);
    } catch (final IOException ioe) {
        logger.error(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage()));
        throw new SmartlingApiException(ioe);
    } finally {
        try {
            if (null != httpClient)
                httpClient.close();
        } catch (final IOException ioe) {
            logger.warn(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage()));
        }
    }
}

From source file:opendap.auth.RemotePDP.java

@Override
public boolean evaluate(String userId, String resourceId, String queryString, String actionId) {

    boolean result = false;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*ww  w . j ava 2s  .c o  m*/

        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(_pdpServiceEndpoint);
        requestUrl.append("?uid=").append(userId);
        requestUrl.append("&resourceId=").append(resourceId);
        requestUrl.append("&query=").append(queryString);
        requestUrl.append("&action=").append(actionId);

        HttpGet httpget = new HttpGet(requestUrl.toString());

        _log.debug("evaluate() - Executing HTTP request: " + httpget.getRequestLine());

        // ----------- Create a custom response handler ----------
        ResponseHandler<Boolean> responseHandler = new ResponseHandler<Boolean>() {

            public Boolean handleResponse(final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {

                    HttpEntity entity = response.getEntity();
                    _log.debug(entity != null ? EntityUtils.toString(entity) : "null");

                    return true;
                } else {
                    return false;
                }
            }

        };
        // -------------------------------------------------------

        result = httpclient.execute(httpget, responseHandler);
    } catch (Exception e) {
        _log.error("evaluate() - Caught {} Message: {}", e.getClass().getName(), e.getMessage());
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            _log.error("evaluate() - Caught {} Message: {}", e.getClass().getName(), e.getMessage());
            // oh well...
        }
    }

    return result;
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP,
        int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {//  ww  w .  j a  v a2s. co  m
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url, Map<String, String> allRequestParams) {
    AtomicReference<String> result = new AtomicReference<>("");
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {/*from  w  w  w  .ja  v a2  s  . com*/
        HttpGet httpGet = new HttpGet(url);
        URIBuilder uriBuilder = new URIBuilder(httpGet.getURI());

        allRequestParams.entrySet().forEach((entry) -> {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value != null) {
                uriBuilder.setParameter(key, value);
            }
        });

        httpGet.setURI(uriBuilder.build());

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getUnexpectedStatus() + status);
            }
        };

        result.set(client.execute(httpGet, responseHandler));
        client.close();

    } catch (IOException | URISyntaxException ex) {
        // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(),
        // ex);
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            // LoggerFactory.getLogger(CustomHttpClientUtil.class).error(ex.getMessage(),
            // ex);
            result.set(hcp.getIoExceptionMessage());
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result.get();
}