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.intellij.translation.translator.TranslatorUtil.java
public static String fetchInfo(String query, TranslatorEx translator) { final CloseableHttpClient client = TranslatorUtil.createClient(); try {//from w ww . j a v a 2 s .c om 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 resEntity = response.getEntity(); return translator.generateSuccess(resEntity); } else { return translator.generateFail(response); } } catch (Exception ignore) { } finally { try { client.close(); } catch (IOException ignore) { } } return null; }
From source file:org.owasp.benchmark.tools.BenchmarkCrawler.java
public static void sendPost(CloseableHttpClient httpclient, HttpPost post) throws Exception { CloseableHttpResponse response = httpclient.execute(post); System.out.println("POST " + post.getURI()); try {//from w ww . j ava 2 s . c o m HttpEntity entity = response.getEntity(); System.out.println("--> (" + response.getStatusLine().getStatusCode() + ") "); EntityUtils.consume(entity); } finally { response.close(); } }
From source file:th.ac.kmutt.chart.rest.application.Main.java
private static void systemConfig(SystemM param) { SystemM sys = param;//from w w w . j av a 2 s . c o m String url = "system"; HttpPost httppost = new HttpPost("http://localhost:8081/ChartServices/rest/" + url); XStream xstream = new XStream(new Dom4JDriver()); Class c = null; try { c = Class.forName(sys.getClass().getName()); } catch (ClassNotFoundException e2) { e2.printStackTrace(); } xstream.processAnnotations(c); ByteArrayEntity entity = null; String xString = xstream.toXML(sys); try { entity = new ByteArrayEntity(xString.getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } httppost.setEntity(entity); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpResponse response = null; HttpEntity resEntity = null; try { response = httpclient.execute(httppost); resEntity = response.getEntity(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //httpclient.getConnectionManager().shutdown(); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } }
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 w w .java2 s . c o 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:org.dbrane.cloud.util.httpclient.HttpClientHelper.java
/** * ?Http/*from www.j ava2 s .c om*/ * * @param request * @return */ private static String getResult(HttpRequestBase request) { CloseableHttpClient httpClient = getHttpClient(); try { CloseableHttpResponse response = httpClient.execute(request); response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity); response.close(); if (200 == response.getStatusLine().getStatusCode()) { return result; } else { throw new BaseException(ErrorType.Httpclient, result); } } return EMPTY_STR; } catch (Exception e) { logger.debug(ErrorType.Httpclient.toString(), e); throw new BaseException(ErrorType.Httpclient, e); } finally { } }
From source file:org.smartloli.kafka.eagle.common.util.TestHttpClientUtils.java
/** * send & get response result.//w w w.ja v a 2s .co m * * @param httpPost */ private static void executeAndGetResponse(HttpPost httpPost) { CloseableHttpClient httpClient = HttpClients.custom().build(); HttpResponse response = null; try { response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(), "utf-8"); LOG.info("dingding server result:" + result); httpClient.close(); } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:downloadwolkflow.getWorkFlowList.java
public static String[] getPageList() { String[] pageList = null;//from www .ja va 2 s. c o m CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet("http://www.myexperiment.org/workflows"); HttpResponse response = httpclient.execute(httpget); String mainpage = EntityUtils.toString(response.getEntity()); Document mainDoc = Jsoup.parse(mainpage); Element pageinfo = mainDoc.select("div.pagination ").first(); // System.out.println(pageinfo.toString()); Elements pagesElemenets = pageinfo.select("[href]"); int pageSize = Integer.parseInt(pagesElemenets.get(pagesElemenets.size() - 2).text()); pageList = new String[pageSize + 1]; for (int i = 1; i <= pageSize; i++) { pageList[i] = "http://www.myexperiment.org/workflows?page=" + i; } } catch (IOException ex) { Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex); } return pageList; }
From source file:de.intevation.irix.ImageClient.java
/** Obtains a Report from mapfish-print service. * * @param imageUrl The url to send the request to. * @param timeout the timeout for the httpconnection. * * @return byte[] with the report./*w w w . ja va 2 s . com*/ * * @throws IOException if communication with print service failed. * @throws ImageException if the print job failed. */ public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException { RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build(); HttpGet get = new HttpGet(imageUrl); CloseableHttpResponse resp = client.execute(get); StatusLine status = resp.getStatusLine(); byte[] retval = null; try { HttpEntity respEnt = resp.getEntity(); InputStream in = respEnt.getContent(); if (in != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[BYTE_ARRAY_SIZE]; int r; while ((r = in.read(buf)) >= 0) { out.write(buf, 0, r); } retval = out.toByteArray(); } finally { in.close(); EntityUtils.consume(respEnt); } } } finally { resp.close(); } if (status.getStatusCode() < HttpURLConnection.HTTP_OK || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) { if (retval != null) { throw new ImageException(new String(retval)); } else { throw new ImageException("Communication with print service '" + imageUrl + "' failed." + "\nNo response from print service."); } } return retval; }
From source file:org.rapidpm.microservice.optionals.service.ServiceWrapper.java
private static String callRest(String restBaseUrl, String adminRestPath) throws IOException { CloseableHttpClient httpClient = HttpClients.createMinimal(); HttpGet httpGet = new HttpGet(restBaseUrl + adminRestPath + "/" + DELAY); final CloseableHttpResponse response = httpClient.execute(httpGet); return IOUtils.toString(response.getEntity().getContent()); }
From source file:com.networknt.client.oauth.TokenHelper.java
public static TokenResponse getToken(TokenRequest tokenRequest) throws ClientException { String url = tokenRequest.getServerUrl() + tokenRequest.getUri(); TokenResponse tokenResponse = null;//from w ww .j av a2 s .com HttpPost httpPost = new HttpPost(url); httpPost.addHeader(Constants.AUTHORIZATION, getBasicAuthHeader(tokenRequest.getClientId(), tokenRequest.getClientSecret())); try { CloseableHttpClient client = Client.getInstance().getSyncClient(); httpPost.setEntity(getEntity(tokenRequest)); HttpResponse response = client.execute(httpPost); tokenResponse = handleResponse(response); } catch (JsonProcessingException jpe) { logger.error("JsonProcessingException: ", jpe); throw new ClientException("JsonProcessingException: ", jpe); } catch (UnsupportedEncodingException uee) { logger.error("UnsupportedEncodingException", uee); throw new ClientException("UnsupportedEncodingException: ", uee); } catch (IOException ioe) { logger.error("IOException: ", ioe); throw new ClientException("IOException: ", ioe); } return tokenResponse; }