List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.carewebframework.fhir.client.HttpClientProxy.java
/** * Silently close a client.// w ww . ja va 2s . c om * * @param client Client to close. */ private void close(CloseableHttpClient client) { try { client.close(); } catch (IOException e) { } }
From source file:org.glowroot.tests.WebDriverSetup.java
private static Container createContainer(int uiPort, File testDir) throws Exception { File adminFile = new File(testDir, "admin.json"); Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}"); Container container;/*from ww w .j a v a2 s . c o m*/ if (Containers.useJavaagent()) { container = new JavaagentContainer(testDir, true, ImmutableList.of()); } else { container = new LocalContainer(testDir, true, ImmutableMap.of()); } // wait for UI to be available (UI starts asynchronously in order to not block startup) CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy()) .build(); Stopwatch stopwatch = Stopwatch.createStarted(); Exception lastException = null; while (stopwatch.elapsed(SECONDS) < 10) { HttpGet request = new HttpGet("http://localhost:" + uiPort); try (CloseableHttpResponse response = httpClient.execute(request); InputStream content = response.getEntity().getContent()) { ByteStreams.exhaust(content); lastException = null; break; } catch (Exception e) { lastException = e; } } httpClient.close(); if (lastException != null) { throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException); } return container; }
From source file:com.dnastack.bob.service.processor.util.HttpUtils.java
/** * Executes GET/POST and obtain the response. * * @param request request// w w w .j av a 2s . co m * * @return response */ public static String executeRequest(HttpRequestBase request) { String response = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; response = httpclient.execute(request, responseHandler); } catch (IOException ex) { // ignore, response already set to null } finally { try { httpclient.close(); } catch (IOException ex) { // ignore } } return response; }
From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java
/** * Ping CAS login URL./* w w w . ja va2 s .com*/ */ public static void pingCasLoginUrl(final BundleContext bundleContext) throws Exception { CloseableHttpClient httpClient = new SecureHttpClient(null, bundleContext).getHttpClient(); HttpGet httpGet = new HttpGet(CAS_LOGIN_URL + "?" + LOCALE); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); Assert.assertEquals(CAS_PING_FAILURE_MESSAGE, HttpServletResponse.SC_OK, httpResponse.getStatusLine().getStatusCode()); } catch (Exception e) { LOGGER.error(CAS_PING_FAILURE_MESSAGE, e); Assert.fail(CAS_PING_FAILURE_MESSAGE); } finally { if (httpResponse != null) { EntityUtils.consume(httpResponse.getEntity()); } httpClient.close(); } }
From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java
public static String doDelete(String url, String charset) { CloseableHttpClient httpClient = null; HttpDelete httpDelete = null;//from www .j ava2s.c o m String result = null; try { httpClient = HttpClientFactory.getSSLClientFactory(); httpDelete = new HttpDelete(url); CloseableHttpResponse response = httpClient.execute(httpDelete); try { if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, charset); } } } catch (Exception e) { log.error("", e); } finally { if (response != null) { response.close(); } } } catch (Exception e) { log.error("doDelete is fail ", e); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { } } } return result; }
From source file:com.gogh.plugin.translator.TranslatorUtil.java
public static ResultEntity fetchEntity(String query, TranslatorEx translator) { final CloseableHttpClient client = TranslatorUtil.createClient(); try {//from www . j a v 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 entity = response.getEntity(); if (entity == null) return null; String json = EntityUtils.toString(entity); try { return new Gson().fromJson(json, ResultEntity.class); } catch (JsonSyntaxException e) { ResultEntity result = new ResultEntity(); result.setErrorCode(ResultEntity.ERROR_CODE_RESTRICTED); return result; } } } catch (Exception ignore) { ignore.printStackTrace(); } finally { try { client.close(); } catch (IOException ignore) { } } return null; }
From source file:com.aws.image.test.TestFlickrAPI.java
public static String callFlickrAPIForEachKeyword(String query, String synsetCode, String safeSearch, int urlsPerKeyword) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; int total = 500; int perPage = 500; System.out.println("\n\t\t KEYWORD::" + query); System.out.println("\t No. of urls required::" + urlsPerKeyword); int totalPages; if (urlsPerKeyword % perPage != 0) totalPages = (urlsPerKeyword / perPage) + 1; else//from w ww. j av a2s . c o m totalPages = urlsPerKeyword / perPage; System.out.println("\n\n\t total pages ::" + totalPages); int currentCount = 0; int eachPage; List<Document> documentsInBatch = new ArrayList<>(); for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) { documentsInBatch = new ArrayList<>(); eachPage = urlsPerKeyword < perPage ? urlsPerKeyword : perPage; StringBuffer sb = new StringBuffer(512); sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=") .append(URLEncoder.encode(query, "UTF-8")).append("&safe_search=").append(safeSearch) .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=").append(eachPage) .append("&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(); 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; 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") : null; if (scrapedImageURL == null) { continue; } String contributor = tempObject.getString("ownername"); String license = tempObject.getString("license"); //System.out.println("Scraped Image URL, need to insert this to Mongo DB --> " + scrapedImageURL); //documentsInBatch.add(getDocumentPerCall(scrapedImageURL, contributor, license, safeSearch)); counter++; } //insertData(documentsInBatch); } System.out.println("F L I C K R C O U N T E R -> " + counter); //insertData(documentsInBatch); //countDownLatchForImageURLs.countDown(); return null; }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the POST way.</p> * /* ww w .j a v a 2 s . co m*/ * @param url request URI * @param json request parameter(json format string) * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String post(String url, String json, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; String result = null; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setEntity(new StringEntity(json, "UTF-8")); httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("POST?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java
private static int countIndexed() { System.out.println("Getting the indexing status"); int indexed = 0; HttpGet statusGet = new HttpGet("http://localhost:9500/unit/_stats"); try {/*from w w w . j ava2s . c om*/ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); System.out.println("Executing request"); HttpResponse response = httpclient.execute(statusGet); System.out.println("Processing response"); InputStream isResponse = response.getEntity().getContent(); BufferedReader isReader = new BufferedReader(new InputStreamReader(isResponse)); StringBuilder strBuilder = new StringBuilder(); String readLine; while ((readLine = isReader.readLine()) != null) { strBuilder.append(readLine); } isReader.close(); System.out.println("Done - reading JSON"); JSONObject esResponse = new JSONObject(strBuilder.toString()); indexed = esResponse.getJSONObject("indices").getJSONObject("unit").getJSONObject("total") .getJSONObject("docs").getInt("count"); System.out.println("Indexed docs: " + indexed); httpclient.close(); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return indexed; }
From source file:io.apiman.gateway.test.PerfOverheadTest.java
/** * Send a bunch of GET requests to the given endpoint and measure the response * time in millis.// w ww. j ava 2s . c o m * @param endpoint * @param numIterations * @throws Exception */ private static int doTest(String endpoint, int numIterations) throws Exception { System.out.print("Testing endpoint " + endpoint + ": \n ["); //$NON-NLS-1$ //$NON-NLS-2$ CloseableHttpClient client = HttpClientBuilder.create().build(); try { long totalResponseTime = 0; for (int i = 0; i < numIterations; i++) { HttpGet get = new HttpGet(endpoint); long start = System.currentTimeMillis(); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Status Code Error: " + response.getStatusLine().getStatusCode()); //$NON-NLS-1$ } response.getAllHeaders(); IOUtils.toString(response.getEntity().getContent()); long end = System.currentTimeMillis(); totalResponseTime += (end - start); System.out.print("-"); //$NON-NLS-1$ if (i % 80 == 0) { System.out.println(""); //$NON-NLS-1$ } } System.out.println("] Total=" + totalResponseTime); //$NON-NLS-1$ return (int) (totalResponseTime / numIterations); } finally { client.close(); } }