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.aws.sampleImage.url.TestHttpGetFlickrAPI.java

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

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;

    int currentCount = 0;

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

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

        System.out.println("URL FORMED --> " + url);

        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;//from w  ww .  java 2s .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
        System.out.println("After making it a valid JSON --> " + responseString);
        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 --> " + scrapedImageURL);

            counter++;
        }

    }

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

From source file:com.k42b3.quantum.worker.HttpWorkerAbstract.java

public void run() {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {// www . ja  v  a 2 s . c om
        this.fetch(httpClient);

        httpClient.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.hazelcast.test.starter.HazelcastVersionLocator.java

private static File downloadFile(String url, File targetDirectory, String filename) {
    CloseableHttpClient client = HttpClients.createDefault();
    File targetFile = new File(targetDirectory, filename);
    if (targetFile.isFile() && targetFile.exists()) {
        return targetFile;
    }/*  w w  w .  j a  v a  2s  . c o m*/
    HttpGet request = new HttpGet(url);
    try {
        CloseableHttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() != SC_OK) {
            throw new GuardianException("Cannot download file from " + url + ", http response code: "
                    + response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        FileOutputStream fos = new FileOutputStream(targetFile);
        entity.writeTo(fos);
        fos.close();
        targetFile.deleteOnExit();
        return targetFile;
    } catch (IOException e) {
        throw rethrowGuardianException(e);
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@Test
public void testNoParamsSucceeds() throws IOException {
    CloseableHttpClient client = HttpClientUtil.createClient(null);
    client.close();
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do post.//from   ww w.  j  av a  2s .  c  o  m
 *
 * @param uri
 *            the uri
 * @param body
 *            the body
 * @param headers
 *            the headers
 * @return the int
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws HttpResponseException
 *             the http response exception
 */
public static int doPost(String uri, String body, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    // TODO delete before commit
    // System.out.println("doPost>> uri:"+uri +"\nbody:"+body+"\n");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    int resp = -1;
    try {
        HttpPost httpPost = new HttpPost(uri);
        for (String key : headers.keySet()) {
            httpPost.addHeader(key, headers.get(key));
            // System.out.println("header:"+key+"/"+headers.get(key));

        }
        // System.out.println("doPost<<");
        httpPost.setEntity(new StringEntity(body));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        resp = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            response.close();
        } else {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {/*  w w w . ja  va2 s .  c o m*/
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

public static String doPost(String url, String data, String contentType, String encoding) {
    StringBuffer buffer = new StringBuffer();
    InputStreamReader is = null;/*from w w  w.  ja  v  a  2s  .  c  o m*/
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        HttpPost post = new HttpPost(url);
        if (data != null) {
            StringEntity entity = new StringEntity(data, encoding);
            post.setHeader("Content-Type", contentType);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:com.seleritycorp.context.RequestUtilsTest.java

@Test
public void testGetHttpClientNonNull() throws IOException {
    replayAll();//from w ww .j a  v  a 2s.co m

    RequestUtils requestUtils = new RequestUtils("https://foo.example.com/");
    CloseableHttpClient httpClient = requestUtils.getHttpClient();

    httpClient.close();

    verifyAll();

    assertThat(httpClient).isNotNull();
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Check service status.//from  w  ww. ja  v  a  2s . c  o m
 *
 * @param endPoint the end point
 * @param client the client (optional) (optional)
 * @return true, if successful
 */
public static boolean checkServiceStatus(String endPoint, CloseableHttpClient client) {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }
    HttpGet request = new HttpGet(endPoint + CheckStatus_URL);

    // add request header
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Accept", ACCEPT);
    HttpResponse response;

    try {
        response = client.execute(request);
    } catch (Exception e) {
        Log.warning(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return false;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }

    if (response.getStatusLine().getStatusCode() == 200) {
        return true;
    } else {
        Log.warning(Log.SERVICE, "INSPIRE service not available: " + endPoint + CheckStatus_URL);
        return false;
    }
}

From source file:com.deying.util.weixin.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    System.out.println("111111111111111111111111111111111111111111111118 ");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12
    try {/*from   w ww.  ja v a  2s  .c  om*/
        keyStore.load(instream, "1233374102".toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".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();
    }
}