List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
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 w w . j av a2 s. co 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.comcast.viper.hlsparserj.PlaylistFactory.java
/** * Returns a playlist inputStream given an httpClient and a URL. * @param httpClient http client//from w w w . j av a 2 s . com * @param url URL to a playlist * @return inputStream * @throws IOException on HTTP connection exception */ private static InputStream getPlaylistInputStream(final CloseableHttpClient httpClient, final URL url) throws IOException { HttpGet get = new HttpGet(url.toString()); CloseableHttpResponse response = null; response = httpClient.execute(get); if (response == null) { throw new IOException("Request returned a null response"); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { response.close(); throw new IOException("Request returned a status code of " + response.getStatusLine().getStatusCode()); } return response.getEntity().getContent(); }
From source file:org.jboss.as.test.clustering.tunnel.singleton.SingletonTunnelTestCase.java
private static String getSingletonNode(URI serviceUri) throws IOException { CloseableHttpClient client = org.jboss.as.test.http.util.TestHttpClientUtils.promiscuousCookieHttpClient(); HttpResponse response = client.execute(new HttpGet(serviceUri)); try {/*from ww w .j a v a 2s . com*/ Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("node"); Assert.assertNotNull("No provider detected.", header); return header.getValue(); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } }
From source file:org.n52.sos.soe.HttpUtil.java
private static InputStream executeGet(String target, CloseableHttpClient client) throws IOException { logger.info("HTTP GET: " + target); long start = System.currentTimeMillis(); HttpGet get = new HttpGet(target); get.setConfig(RequestConfig.custom().setConnectTimeout(1000 * 120).build()); HttpResponse resp = client.execute(get); logger.info("Request latency: " + (System.currentTimeMillis() - start)); return resp.getEntity().getContent(); }
From source file:eu.citadel.converter.io.index.CitadelIndexUtil.java
/** * Get the list of city allowed by citadel index * @param url The url that host the city list * @return List of allowed city sorted by name * @throws ConverterException//from w w w . j a va 2 s .c om */ public static List<CitadelCityInfo> getCitadelCityInfo(String url) throws ConverterException { try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost request = new HttpPost(url); CloseableHttpResponse response = httpclient.execute(request); String jsonResponse = EntityUtils.toString(response.getEntity()); Gson gson = new GsonBuilder().create(); if (jsonResponse.length() < 11) { log.error("Invalid response from server: " + jsonResponse + "."); throw new ConverterException("Invalid response from server: " + jsonResponse + "."); } jsonResponse = jsonResponse.substring(10, jsonResponse.length() - 1); List<CitadelCityInfo> infos = gson.fromJson(jsonResponse, new TypeToken<List<CitadelCityInfo>>() { }.getType()); Collections.sort(infos); return infos; } catch (ParseException | IOException e) { log.error(e.getMessage()); throw new ConverterException(e.getMessage()); } }
From source file:com.lagrange.LabelApp.java
private static void sendPhotoToTelegramBot() { File file = new File(pathToImage.toUri()); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("photo", file, ContentType.create("image/jpeg"), file.getName()) .addTextBody("chat_id", CHAT_ID).build(); String urlSendPhoto = "https://api.telegram.org/" + BOT_ID + "/sendPhoto"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlSendPhoto); httpPost.setEntity(httpEntity);//from w ww . j a v a2 s . c o m try { CloseableHttpResponse response = httpclient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done sending photo"); }
From source file:io.github.thred.climatetray.ClimateTrayUtils.java
public static BuildInfo performBuildInfoRequest() { try {//from ww w.j a v a 2 s . co m CloseableHttpClient client = ClimateTray.PREFERENCES.getProxySettings().createHttpClient(); HttpGet request = new HttpGet(BUILD_INFO_URL); CloseableHttpResponse response; try { response = client.execute(request); } catch (IOException e) { ClimateTray.LOG.warn("Failed to request build information from \"%s\".", e, BUILD_INFO_URL); consumeUpdateFailed(); return null; } try { int status = response.getStatusLine().getStatusCode(); if ((status >= 200) && (status < 300)) { try (InputStream in = response.getEntity().getContent()) { BuildInfo buildInfo = BuildInfo.create(in); ClimateTray.LOG.info("Build Information: %s", buildInfo); return buildInfo; } } else { ClimateTray.LOG.warn("Request to \"%s\" failed with error %d.", BUILD_INFO_URL, status); consumeUpdateFailed(); } } finally { response.close(); } } catch (Exception e) { ClimateTray.LOG.warn("Failed to request build information.", e); } return null; }
From source file:org.geosamples.credentials.CredentialsValidator.java
/** * Validates user credentials for use with GeoPass from SESAR. * * @see//w w w . jav a2 s . c o m * <a href="http://www.iedadata.org/services/sesar_api#2.sesarusercredential">SESAR * credential POST API</a> * @param userName * @param password * @param credentialsService * @return ArrayList of user codes for this user * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws KeyManagementException */ private static ArrayList<String> validateUserCredentials(String userName, String password, String credentialsService) throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { ArrayList<String> userCodes = new ArrayList<>(); Map<String, String> dataToPost = new HashMap<>(); dataToPost.put("username", userName); dataToPost.put("password", password); org.apache.http.client.methods.HttpPost httpPost = new HttpPost(credentialsService); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpClient httpClient = org.geosamples.utilities.HTTPClient.clientWithNoSecurityValidation(); Document doc; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { HttpEntity myEntity = httpResponse.getEntity(); InputStream response = myEntity.getContent(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); doc = factory.newDocumentBuilder().parse(response); EntityUtils.consume(myEntity); } if (doc != null) { if (doc.getElementsByTagName("valid").getLength() > 0) { if (doc.getElementsByTagName("valid").item(0).getTextContent().trim().equalsIgnoreCase("yes")) { NodeList userCodesList = doc.getElementsByTagName("user_code"); for (int i = 0; i < userCodesList.getLength(); i++) { userCodes.add(userCodesList.item(i).getTextContent().trim()); } } } } return userCodes; }
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./* ww w.j ava 2 s .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(); } }
From source file:org.duracloud.syncui.SyncUIDriver.java
private static boolean isAppRunning(String url, CloseableHttpClient client) { HttpGet get = new HttpGet(url); CloseableHttpResponse response;/*from w w w . jav a 2 s.c o m*/ int responseCode; try { response = client.execute(get); responseCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { log.debug("Attempt to connect to synctool app at url " + url + " failed due to: " + e.getMessage()); responseCode = 0; } log.debug("Response from {}: {}", url, responseCode); return responseCode == 200; }