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.vmware.identity.rest.core.client.RequestExecutor.java
private static <T> T executeInternal(CloseableHttpClient client, HttpUriRequest request, JavaType type) throws ClientProtocolException, WebApplicationException, HttpException, IOException { CloseableHttpResponse response = client.execute(request); try {/*from w ww . j a v a 2 s. c o m*/ int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) { return handleSuccess(response, type); } else { throw handleError(response, response.getStatusLine().getStatusCode()); } } finally { response.close(); } }
From source file:org.wuspba.ctams.ui.server.ServerUtils.java
public static String get(URI uri) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(uri); String ret;/*from w w w . j a v a2 s. c o m*/ try (CloseableHttpResponse response = httpclient.execute(httpGet)) { HttpEntity entity = response.getEntity(); ret = ServerUtils.convertEntity(entity); EntityUtils.consume(entity); } return ret; }
From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPIProfile.java
private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; long httpCallTime = 0L; long jsonParseTime = 0L; 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) { long startHttpCall = System.currentTimeMillis(); 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()); long endHttpCall = System.currentTimeMillis(); httpCallTime = (long) (httpCallTime + (long) (endHttpCall - startHttpCall)); long startJsonParse = System.currentTimeMillis(); BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;/*from ww w . j a va 2 s. com*/ 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++; } long endJsonParse = System.currentTimeMillis(); jsonParseTime = (long) (jsonParseTime + (long) (endJsonParse - startJsonParse)); } System.out.println("C O U N T E R -> " + counter); System.out.println("HTTP CALL TIME --> " + httpCallTime + " JSON PARSE TIME --> " + jsonParseTime); return null; }
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);// w w w . j a va 2 s .com 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:com.gogh.plugin.translator.TranslatorUtil.java
public static ResultEntity fetchEntity(String query, TranslatorEx translator) { final CloseableHttpClient client = TranslatorUtil.createClient(); try {/* w w w . ja 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 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:org.wuspba.ctams.ui.server.ServerUtils.java
public static String delete(URI uri) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(uri); String ret;/*from w w w. j a va 2s. com*/ try (CloseableHttpResponse response = httpclient.execute(httpDelete)) { HttpEntity responseEntity = response.getEntity(); ret = convertEntity(responseEntity); EntityUtils.consume(responseEntity); } return ret; }
From source file:org.rapidoid.http.HTTP.java
public static byte[] get(String uri) { try {/* www. j ava2 s . c o m*/ CloseableHttpClient client = client(uri); HttpGet get = new HttpGet(uri); Log.info("Starting HTTP GET request", "request", get.getRequestLine()); CloseableHttpResponse response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } catch (Throwable e) { throw U.rte(e); } }
From source file:org.codehaus.mojo.license.utils.HttpRequester.java
/** * this method will send a simple GET-request to the given destination and will return the result as a * string//from w w w . j a v a 2 s .c om * * @param url the resource destination that is expected to contain pure text * @return the string representation of the resource at the given URL */ public static String getFromUrl(String url) throws MojoExecutionException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); CloseableHttpResponse response = null; String result = null; try { response = httpClient.execute(get); result = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")); } catch (ClientProtocolException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (response != null) { try { response.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } return result; }
From source file:no.kantega.commons.util.XMLHelper.java
public static Document openDocument(URL url) throws SystemException { Document doc = null;/* w ww .j a v a 2 s. c o m*/ CloseableHttpClient httpClient = getHttpClient(); try (CloseableHttpResponse execute = httpClient.execute(new HttpGet(url.toURI()))) { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = docFactory.newDocumentBuilder(); doc = builder.parse(execute.getEntity().getContent()); } catch (Exception e) { log.error("Error opening XML document from URL", e); throw new SystemException("Error opening XML document from URL", e); } return doc; }
From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java
/** * Download from given URL to given file location. * @param url String//w ww . ja v a2s . c o m * @param filepath String * @return */ public static String download(String url, String filepath) { String status = ""; try { CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (filepath == null) { filepath = getFilePath(response); //NOSONAR } File file = new File(filepath); file.getParentFile().mkdirs(); FileOutputStream fileout = new FileOutputStream(file); byte[] buffer = new byte[CACHE]; int ch; while ((ch = is.read(buffer)) != -1) { fileout.write(buffer, 0, ch); } is.close(); fileout.flush(); fileout.close(); status = Constant.DOWNLOADCSAR_SUCCESS; } catch (Exception e) { status = Constant.DOWNLOADCSAR_FAIL; LOG.error("Download csar file failed! " + e.getMessage(), e); } return status; }