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:no.api.meteo.client.DefaultMeteoClient.java

private void closeClient(CloseableHttpClient client) {
    try {/*  w w w. j  a  v  a 2s .  com*/
        if (client != null) {
            client.close();
        }
    } catch (IOException e) {
        log.warn("Could not close http client. This might cause trouble further down.", e);
    }
}

From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java

@Override
@SuppressWarnings("resource")
public void close() {
    CloseableHttpClient currentClient = this.getHttpClient();
    if (currentClient != null) {
        try {// w w w  . ja  va2s.c o  m
            currentClient.close();
        } catch (Exception e) {
            log.trace("Cannot close HttpClient", e);
        }
    }
}

From source file:org.dasein.cloud.utils.requester.AbstractDaseinRequestExecutor.java

protected T execute(HttpUriRequest httpUriRequest) throws DaseinRequestException {
    httpClientBuilder = setProxyIfRequired(httpClientBuilder);

    try {//from   w ww.ja  va2s. c o m
        CloseableHttpClient httpClient = this.httpClientBuilder.build();
        try {
            return httpClient.execute(httpUriRequest, this.responseHandler);
        } finally {
            httpClient.close();
        }
    } catch (Exception e) {
        throw new DaseinRequestException(e.getMessage(), e);
    }
}

From source file:com.aws.sampleImage.url.LambdaFunctionImageURLCrawlerHandler.java

private static String callFlickrAPIForEachKeyword(String query, String synsetCode)
        throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;//For monitoring purposes only

    int currentCount = 0;

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {

        StringBuffer sb = new StringBuffer(512);
        sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=").append(query)
                .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=").append(i)
                .append("&format=json&api_key=").append(apiKey).append("&api_secret=").append(apiSecret)
                .append("&license=4,5,6,7,8");

        String url = sb.toString();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;/*w w w .j ava2 s . co  m*/
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        //System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        //System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : "";

            //System.out.println("Scraped Image URL, need to insert this to Amazon DYnamo DB --> " + scrapedImageURL);

            counter++;

            insertScrapedImageURLsInDynamoDB(scrapedImageURL, synsetCode, query);
        }

    }

    System.out.println("C O U N T E R -> " + counter);
    return null;
}

From source file:com.huotu.mallduobao.common.thirdparty.ClientCustomSSL.java

public static String doRefund(String url, String data, String celPath, String celPassword) throws Exception {
    /**/*www .  jav  a  2s.c o m*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(celPath));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, celPassword.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, celPassword.toCharArray())//?
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.simple.weixin.refund.ClientCustomSSL.java

public static String doRefund(String password, String keyStrore, String url, String data) throws Exception {
    /**// w w w . j av a2  s  .co  m
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(keyStrore));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, password.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.restfiddle.handler.http.GetHandler.java

public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
    RfResponseDTO response = null;/*from  ww w .j  a  v a  2s .c o m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(rfRequestDTO.getApiUrl());
    try {
        response = processHttpRequest(httpGet, httpclient);

    } finally {
        httpclient.close();
    }
    return response;
}

From source file:cn.digirun.frame.payment.wxpay.util.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    /**/*from  www .  j  a  v a2 s.  co m*/
     * ?PKCS12? ?-- API 
     */
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    /**
     * ?
     */
    //ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ "");
    //      FileInputStream instream = new FileInputStream(new File("D:/Program Files/MyEclipse 6.5/workspace/weidian/WebRoot/cer/apiclient_cert.p12"));//P12
    FileInputStream instream = new FileInputStream(
            ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + WxpayConfig.cert_path));
    try {
        /**
         * ?
         * MCHID
         * */
        keyStore.load(instream, WxpayConfig.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WxpayConfig.mch_id.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??

        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:net.officefloor.plugin.socket.server.http.server.MockHttpServer.java

@Override
protected void tearDown() throws Exception {
    // Shutdown the HTTP Clients
    for (CloseableHttpClient client : this.httpClients) {
        client.close();
    }/*from   w  w w.  j a v a  2s. c om*/

    // Clean up parent
    super.tearDown();
}

From source file:org.apache.synapse.samples.framework.clients.BasicHttpClient.java

/**
 * Make a HTTP GET request on the specified URL.
 *
 * @param url A valid HTTP URL/*w  w  w.  j  ava2  s.  c  o m*/
 * @return A HttpResponse object
 * @throws Exception If an error occurs while making the HTTP call
 */
public HttpResponse doGet(String url) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpGet get = new HttpGet(url);
        return new HttpResponse(client.execute(get));
    } finally {
        client.close();
    }
}