Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getTokenFromRefreshToken() {
    access_token = null;//from  w  w  w. j a v a2  s.  c  o  m
    expires_in = -1;
    token_start_time = -1;

    if (gProps == null) {
        initGProps();
    }

    /* Try refresh token */
    // Query for token now that user has gone through browser part
    // of
    // flow

    // The method used in getTokensFromCode should work here as well - I
    // think URL encoded Form is the recommended way...
    HttpPost post = new HttpPost(gProps.token_uri);
    post.addHeader("accept", "application/json");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("client_id", gProps.client_id));
    nameValuePairs.add(new BasicNameValuePair("client_secret", gProps.client_secret));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token));
    nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        try {
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseJSON = EntityUtils.toString(resEntity);
                    ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                    access_token = root.get("access_token").asText();
                    // refresh_token =
                    // root.get("refresh_token").asText();
                    token_start_time = System.currentTimeMillis() / 1000;
                    expires_in = root.get("expires_in").asInt();
                }
            } else {
                log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
                HttpEntity resEntity = response.getEntity();
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            log.error("Error obtaining access token: " + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    } catch (IOException io) {
        log.error("Error closing connections: " + io.getMessage());
    }
}

From source file:eu.seaclouds.platform.planner.core.utils.HttpHelper.java

/**
 * @param restPath//from  w  w w . j  a v  a  2  s.co m
 * @param params
 * @return
 */
public String getRequest(String restPath, List<NameValuePair> params) {
    log.info("Getting request for " + this.serviceURL + restPath);

    HttpGet httpGet = new HttpGet(prepareRequestURL(restPath, params));
    CloseableHttpResponse response = null;
    String content = "";
    try {
        response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        content = new Scanner(entity.getContent()).useDelimiter("\\Z").next();
        EntityUtils.consume(entity);
        log.info("Request executed succesfully");
    } catch (IOException e) {
        log.error("IOException", e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            log.error("IOEXception", e);
        }
    }
    return content;
}

From source file:co.cask.cdap.client.rest.RestStreamClient.java

@Override
public long getTTL(String stream) throws IOException {
    HttpGet getRequest = new HttpGet(restClient.getBaseURL()
            .resolve(String.format("/%s/streams/%s/info", restClient.getVersion(), stream)));
    CloseableHttpResponse httpResponse = restClient.execute(getRequest);
    long ttl;/*from  w w  w  .java2  s.c  o m*/
    try {
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Get TTL Response Code : {}", responseCode);
        RestClient.responseCodeAnalysis(httpResponse);
        JsonObject jsonContent = RestClient.toJsonObject(httpResponse.getEntity());
        ttl = jsonContent.get(TTL_ATTRIBUTE_NAME).getAsLong();
    } finally {
        httpResponse.close();
    }
    return ttl;
}

From source file:net.orzo.data.Web.java

/**
 *
 *//*from  www  .j  a  v  a2 s .  c o  m*/
public String get(String URL) {
    HttpGet httpget = new HttpGet(URL);
    CloseableHttpResponse response = null;
    HttpEntity httpEntity;
    String result = null;

    try {
        response = this.httpClient.execute(httpget);
        httpEntity = response.getEntity();
        if (httpEntity != null) {
            httpEntity = new BufferedHttpEntity(httpEntity);
            result = EntityUtils.toString(httpEntity);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);

    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOG.warn(String.format("Failed to close response object: %s", e));
            }
        }
    }
    return result;
}

From source file:org.gradle.cache.tasks.http.HttpTaskOutputCache.java

@Override
public boolean load(TaskCacheKey key, TaskOutputReader reader) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//  ww w . j  a va 2 s .com
        final URI uri = root.resolve("./" + key.getHashCode());
        HttpGet httpGet = new HttpGet(uri);
        final CloseableHttpResponse response = httpClient.execute(httpGet);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for GET {}: {}", uri, response.getStatusLine());
        }
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                reader.readFrom(response.getEntity().getContent());
                return true;
            } else {
                return false;
            }
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
}

From source file:cn.org.once.cstack.cli.rest.RestUtils.java

public Map<String, String> sendGetFileCommand(String url, String filePath, Map<String, Object> parameters)
        throws ManagerResponseException {
    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    try {//from  w w  w  .ja  va  2 s .co  m
        CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext);
        InputStream inputStream = httpResponse.getEntity().getContent();
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        int inByte;
        while ((inByte = inputStream.read()) != -1)
            fos.write(inByte);
        inputStream.close();
        fos.close();
        httpResponse.close();

    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:org.wltea.analyzer.dic.Dictionary.java

/**
 * ???//from   w w w  .ja v  a  2 s.  c  o m
 */
private static List<String> getRemoteWords(String location) {

    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
            .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {

            String charset = "UTF-8";
            // ??utf-8
            if (response.getEntity().getContentType().getValue().contains("charset=")) {
                String contentType = response.getEntity().getContentType().getValue();
                charset = contentType.substring(contentType.lastIndexOf("=") + 1);
            }
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                buffer.add(line);
            }
            in.close();
            response.close();
            return buffer;
        }
        response.close();
    } catch (ClientProtocolException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IllegalStateException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IOException e) {
        logger.error("getRemoteWords {} error", e, location);
    }
    return buffer;
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.request.AbstractAuthHttpRequest.java

/**
 * Execute the request and all following requests in the sequence.
 *
 * @param client//  w w w .ja v  a 2  s.  c o m
 *          HTTP Client
 * @throws IOException
 *          in case of a problem or the connection was aborted
 * @throws ClientProtocolException
 *          in case of an http protocol error
 */
public final CloseableHttpResponse executeSequence(final CloseableHttpClient client)
        throws IOException, ClientProtocolException {
    // TODO : throw exception if initialization is incorrect
    init();
    CloseableHttpResponse response = null;

    try {
        response = client.execute(httpRequest);
        final HttpEntity entity = response.getEntity();

        // TODO: check the status line

        if (nextRequest != null) {
            nextRequest.configFromPreviousResponse(entity);
            EntityUtils.consume(entity);
        }

    } finally {
        // Close the resource before executing the next request
        if (response != null && nextRequest != null) {
            response.close();
        }
    }

    CloseableHttpResponse lastResponse;
    if (nextRequest != null) {
        lastResponse = nextRequest.executeSequence(client);
    } else {
        lastResponse = response;
    }

    return lastResponse;
}

From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java

protected byte[] execute(HttpUriRequest request) throws IOException {
    Log.w(TAG, "connecting to " + apn.getMmsc());

    CloseableHttpClient client = null;/*from w w w  .j  ava2 s .c om*/
    CloseableHttpResponse response = null;
    try {
        client = constructHttpClient();
        response = client.execute(request);

        Log.w(TAG, "* response code: " + response.getStatusLine());

        if (response.getStatusLine().getStatusCode() == 200) {
            return parseResponse(response.getEntity().getContent());
        }
    } finally {
        if (response != null)
            response.close();
        if (client != null)
            client.close();
    }

    throw new IOException("unhandled response code");
}