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

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

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.jiuyi.qujiuyi.common.util.WxRefundSSL.java

public final static String post(String entity, String mch_id, Integer clientType) throws Exception {
    try {//  w  w w .jav  a2s  .  co m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // FileInputStream instream = new FileInputStream(new
        // File("D:\\apiclient_cert.p12"));

        FileInputStream instream = null;

        if (clientType == 0) {
            instream = new FileInputStream(new File(SysCfg.getString("apiclient.ssl")));
        } else {
            instream = new FileInputStream(new File(SysCfg.getString("apiclient.app.ssl")));
        }

        try {
            keyStore.load(instream, mch_id.toCharArray());
        } finally {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();

        sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    String result = "";
    try {
        HttpPost post = new HttpPost(SysCfg.getString("weixin.refund"));
        post.setEntity(new StringEntity(entity));
        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity resp = response.getEntity();
            if (resp != null) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resp.getContent()));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            }
            EntityUtils.consume(resp);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:org.drftpd.util.HttpUtils.java

public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);// www .ja va 2 s.  co  m
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

/**
 * @param url    The URL to check//  w  ww  . j  a va  2 s. c o m
 * @param client Http client to use
 * @return True if the url points to an S3 repository.
 */
public static boolean isS3Repository(String url, CloseableHttpClient client) {
    HttpHead headMethod = new HttpHead(HttpUtils.encodeQuery(url));
    try (CloseableHttpResponse response = client.execute(headMethod)) {
        Header s3RequestId = response.getFirstHeader(HEADER_S3_REQUEST_ID);
        return s3RequestId != null;
    } catch (IOException e) {
        log.debug("Failed detecting S3 repository: " + e.getMessage(), e);
    }
    return false;
}

From source file:org.nuxeo.elasticsearch.http.readonly.HttpClient.java

public static String get(String url, String payload) throws IOException {
    if (payload == null) {
        return get(url);
    }/* w w w.  j  ava2  s  . c om*/
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGetWithEntity e = new HttpGetWithEntity(url);
    StringEntity myEntity = new StringEntity(payload,
            ContentType.create(MediaType.APPLICATION_FORM_URLENCODED, UTF8_CHARSET));
    e.setEntity(myEntity);
    try (CloseableHttpResponse response = client.execute(e)) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    }
}

From source file:io.fabric8.apps.infinispan.InfinispanServerKubernetesTest.java

/**
 * Method that puts a String value in cache.
 *//*from w  ww  .j  a v a  2s  .c o m*/
public static void putMethod(String serverURL, String key, String value) throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPut put = new HttpPut(serverURL + "/" + key);
    put.addHeader(new BasicHeader("Content-Type", "text/plain"));
    put.setEntity(new StringEntity(value));
    client.execute(put);
}

From source file:com.lhings.java.http.WebServiceCom.java

private static HttpResponse executeRequest(HttpRequestBase request) throws IOException {
    CloseableHttpClient hc = HttpClients.createDefault();
    CloseableHttpResponse response = hc.execute(request);
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setStatusCode(response.getStatusLine().getStatusCode());
    httpResponse.setStatusMessage(response.getStatusLine().getReasonPhrase());
    // ResponseHandler<String> handler = new BasicResponseHandler();
    // String responseBody = handler.handleResponse(response);
    httpResponse.setResponseBody(EntityUtils.toString(response.getEntity()));
    return httpResponse;
}

From source file:edu.cmu.lti.oaqa.bioqa.providers.kb.TmToolConceptProvider.java

private static String submitText(String trigger, String text) throws IOException {
    CloseableHttpClient client = clientBuilder.build();
    HttpPost post = new HttpPost(URL_PREFIX + trigger + "/Submit/");
    post.setEntity(new StringEntity(text));
    HttpResponse response = client.execute(post);
    String session = IOUtils.toString(response.getEntity().getContent());
    HttpGet get = new HttpGet(URL_PREFIX + session + "/Receive/");
    response = client.execute(get);/*  w  ww.  j  a va  2  s .  c om*/
    return IOUtils.toString(response.getEntity().getContent());
}

From source file:eionet.gdem.utils.HttpUtils.java

/**
 * Method checks whether the resource behind the given URL exist. The method calls HEAD request and if the resonse code is 200,
 * then returns true. If exception is thrown or response code is something else, then the result is false.
 *
 * @param url URL// w w w.ja v a2s  . c  o  m
 * @return True if resource behind the url exists.
 */
public static boolean urlExists(String url) {

    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpHead method = new HttpHead(url);
    CloseableHttpResponse response = null;
    try {
        // Execute the method.
        response = client.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_OK;
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            return false;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        method.releaseConnection();
        try {
            response.close();
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:org.keycloak.helper.TestsHelper.java

public static boolean returnsForbidden(String endpoint) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {//from w  w  w  . ja v a  2 s. c o  m
        HttpGet get = new HttpGet(baseUrl + endpoint);
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == 403
                || response.getStatusLine().getStatusCode() == 401) {
            return true;
        } else {
            return false;
        }

    } finally {
        client.close();
    }
}

From source file:com.worldsmostinterestinginfographic.util.OAuth2Utils.java

/**
 * Request an access token from the given token endpoint.
 *
 * The token endpoint given must contain all of the required properties necessary for the request.  At a minimum,
 * this will include:/* w  ww  .j  ava 2  s.c o  m*/
 *
 *   grant_type
 *   code
 *   redirect_uri
 *   client_id
 *
 * If the authorization code is valid and the request is successful, the access token value will be parsed from the
 * response and returned.  If the request has failed for any reason, null will be returned.
 *
 * @param tokenEndpoint The full token endpoint, with required parameters for making the access token request
 * @return A valid access token if the request was successful; null otherwise.
 */
public static String requestAccessToken(String tokenEndpoint) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        // Exchange authorization code for access token
        HttpPost httpPost = new HttpPost(tokenEndpoint);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String line = bufferedReader.readLine();

        // Detect error message
        if (line.toLowerCase().contains("\"error\"")) {
            log.severe("Fatal exception occurred while making the access token request: " + line);
            return null;
        }

        // Extract access token
        String accessToken = line.split("&")[0].split("=")[1];
        if (StringUtils.isEmpty(accessToken)) {
            log.severe(
                    "Fatal exception occurred while making the access token request: Access token value in response is empty");
            return null;
        }

        return accessToken;
    } catch (Exception e) {
        log.severe("Fatal exception occurred while making the access token request: " + e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            log.severe("Fatal exception occurred while closing HTTP client connection: " + e.getMessage());
            e.printStackTrace();
        }
    }

    return null;
}