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.atomiton.watermanagement.ngo.util.HttpRequestResponseHandler.java

public static String sendPost(String serverURL, String postBody) throws Exception {

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(serverURL);

    StringEntity entity = new StringEntity(postBody, "UTF-8");

    post.setEntity(entity);//from  w ww .ja  v a 2s. c om

    HttpResponse response = client.execute(post);
    // System.out.println("\nSending 'POST' request to URL : " + serverURL);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    client.close();
    // System.out.println(result.toString());
    return result.toString();
}

From source file:org.openo.nfvo.monitor.umc.monitor.common.HttpClientUtil.java

/**
 * @Title httpDelete/*from w  w w .  j  a v  a  2 s  . co  m*/
 * @Description TODO(realize the rest interface to access by httpDelete)
 * @param url
 * @return
 * @throws Exception
 * @return int (return StatusCode,If zero error said)
 */
public static int httpDelete(String url) throws Exception {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(url);
    try {
        CloseableHttpResponse res = httpClient.execute(httpDelete);
        try {
            return res.getStatusLine().getStatusCode();
        } finally {
            res.close();
        }
    } catch (ParseException e) {
        LOGGER.error("HttpClient throw ParseException:" + url, e);
    } catch (IOException e) {
        LOGGER.error("HttpClient throw IOException:" + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error("HttpClient Close throw IOException", e);
        }
    }

    return 0;

}

From source file:com.intellij.translation.translator.TranslatorUtil.java

public static String fetchInfo(String query, TranslatorEx translator) {
    final CloseableHttpClient client = TranslatorUtil.createClient();
    try {/* w  w w . j  a va 2 s .  c  o m*/
        final URI queryUrl = translator.createUrl(query);
        HttpGet httpGet = new HttpGet(queryUrl);
        HttpResponse response = client.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity resEntity = response.getEntity();
            return translator.generateSuccess(resEntity);
        } else {
            return translator.generateFail(response);
        }
    } catch (Exception ignore) {
    } finally {
        try {
            client.close();
        } catch (IOException ignore) {
        }
    }
    return null;
}

From source file:co.aurasphere.botmill.skype.util.network.NetworkUtils.java

/**
 * Send.//www  .j  a  va  2s. c  om
 *
 * @param request the request
 * @return the string
 */
private static String send(HttpRequestBase request) {

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(null, null);

    provider.setCredentials(AuthScope.ANY, credentials);
    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    logger.debug(request.getRequestLine().toString());
    HttpResponse httpResponse = null;
    String response = null;
    try {
        httpResponse = httpClient.execute(request);
        response = logResponse(httpResponse);
    } catch (Exception e) {
        logger.error("Error during HTTP connection to Kik: ", e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("Error while closing HTTP connection: ", e);
        }
    }
    return response;
}

From source file:com.turn.ttorrent.common.Utils.java

/**
 * Resolves a file from URI and returns its byte array.
 * /*from  w  ww  . java  2 s .c o  m*/
 * @param uri
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static byte[] resolveUrlFileToByteArray(URI uri) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        HttpGet get = new HttpGet(uri);
        HttpResponse response = httpclient.execute(get);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream inputStream = entity.getContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);
            return outputStream.toByteArray();
        }

        throw new IOException("Could not resolve file... [" + uri + "]");

    } finally {
        httpclient.close();
    }

}

From source file:co.aurasphere.botmill.telegram.internal.util.network.NetworkUtils.java

/**
 * Sends a request./*  w w w .j a v  a 2s  .  c o m*/
 * 
 * @param request
 *            the request to send
 * @return response the response.
 */
private static String send(HttpRequestBase request) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    logger.debug(request.getRequestLine().toString());
    HttpResponse httpResponse = null;
    String response = null;
    try {
        httpResponse = httpClient.execute(request);
        response = logResponse(httpResponse);
    } catch (Exception e) {
        logger.error("Error during HTTP connection to Telegram: ", e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("Error while closing HTTP connection: ", e);
        }
    }
    return response;
}

From source file:co.aurasphere.botmill.util.NetworkUtils.java

/**
 * Send./* w w w. jav a  2 s  .com*/
 *
 * @param request
 *            the request
 * @return the string
 */
private static String send(HttpRequestBase request) {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    logger.debug(request.getRequestLine().toString());
    HttpResponse httpResponse = null;
    String response = null;
    try {
        httpResponse = httpClient.execute(request);
        response = logResponse(httpResponse);
    } catch (Exception e) {
        logger.error("Error during HTTP connection to RASA: ", e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("Error while closing HTTP connection: ", e);
        }
    }
    return response;
}

From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java

/**
 * Send request by post method./*from  ww w  . j  a v  a2 s .com*/
 * 
 * @param uri:
 *            http://ip:port/demo
 * @param parames:
 *            new BasicNameValuePair("code", "200")
 * 
 *            new BasicNameValuePair("name", "smartloli")
 */
public static String doPostForm(String uri, List<BasicNameValuePair> parames) {
    String result = "";
    try {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Do post form request has error, msg is " + e.getMessage());
    }
    return result;
}

From source file:com.gogh.plugin.translator.TranslatorUtil.java

public static String fetchInfo(String query, TranslatorEx translator) {
    final CloseableHttpClient client = TranslatorUtil.createClient();
    try {/*from w  w w .  j av  a2  s  .  c  o  m*/
        final URI queryUrl = translator.createUrl(query);
        HttpGet httpGet = new HttpGet(queryUrl);
        HttpResponse response = client.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity resEntity = response.getEntity();
            return translator.generateSuccess(resEntity);
        } else {
            return translator.generateFail(response);
        }
    } catch (Exception ignore) {
        ignore.printStackTrace();
    } finally {
        try {
            client.close();
        } catch (IOException ignore) {
        }
    }
    return null;
}

From source file:com.portfolio.data.utils.PostForm.java

public static boolean updateResource(String sessionid, String backend, String uuid, String lang, String json)
        throws Exception {
    /// Parse and create xml from JSON
    JSONObject files = (JSONObject) JSONValue.parse(json);
    JSONArray array = (JSONArray) files.get("files");

    if ("".equals(lang) || lang == null)
        lang = "fr";

    JSONObject obj = (JSONObject) array.get(0);
    String ressource = "";
    String attLang = " lang=\"" + lang + "\"";
    ressource += "<asmResource>" + "<filename" + attLang + ">" + obj.get("name") + "</filename>" + // filename
            "<size" + attLang + ">" + obj.get("size") + "</size>" + "<type" + attLang + ">" + obj.get("type")
            + "</type>" +
            //      obj.get("url");   // Backend source, when there is multiple backend
            "<fileid" + attLang + ">" + obj.get("fileid") + "</fileid>" + "</asmResource>";

    /// Send data to resource
    /// Server + "/resources/resource/file/" + uuid +"?lang="+ lang
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from w ww.j a  va 2 s . c  om*/
        HttpPut put = new HttpPut("http://" + backend + "/rest/api/resources/resource/" + uuid);
        put.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us

        StringEntity se = new StringEntity(ressource);
        se.setContentEncoding("application/xml");
        put.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(put);

        try {
            HttpEntity resEntity = response.getEntity();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    return false;
}