List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:azkaban.utils.RestfulApiClient.java
/** function to dispatch the request and pass back the response. * *///from w ww.java 2 s. co m protected T sendAndReturn(HttpUriRequest request) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); try { return this.parseResponse(client.execute(request)); } finally { client.close(); } }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
private static long getLastModified(URL url) { CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try {/* w w w . ja va2 s.c o m*/ HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Builder builder = RequestConfig.custom(); HttpHost proxy = getProxy(target); if (proxy != null) { builder = builder.setProxy(proxy); } RequestConfig config = builder.build(); HttpHead request = new HttpHead(url.toURI()); request.setConfig(config); response = httpclient.execute(target, request); Header[] s = response.getHeaders("last-modified"); if (s != null && s.length > 0) { String lastModified = s[0].getValue(); return new Date(lastModified).getTime(); } } catch (Exception e) { logWarning(e); return -1; } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } try { httpclient.close(); } catch (IOException e) { } } return -1; }
From source file:br.bireme.scl.CheckUrl.java
public static int check(final String url) { if (url == null) { throw new NullPointerException(); }/*from w w w. ja v a2 s . c o m*/ final CloseableHttpClient httpclient = HttpClients.createDefault(); int responseCode = -1; try { //final HttpHead httpX = new HttpHead(fixUrl(url)); // Some servers return 500 final HttpGet httpX = new HttpGet(fixUrl(url)); httpX.setConfig(CONFIG); httpX.setHeader(new BasicHeader("User-Agent", "Wget/1.16.1 (linux-gnu)")); httpX.setHeader(new BasicHeader("Accept", "*/*")); httpX.setHeader(new BasicHeader("Accept-Encoding", "identity")); httpX.setHeader(new BasicHeader("Connection", "Keep-Alive")); // Create a custom response handler final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() { @Override public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { return response.getStatusLine().getStatusCode(); } }; responseCode = httpclient.execute(httpX, responseHandler); } catch (Exception ex) { responseCode = getExceptionCode(ex); } finally { try { httpclient.close(); } catch (Exception ioe) { } } return responseCode; }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsConsumerWithBeanTest.java
private void sendPutRequest(String uri) throws Exception { HttpPut put = new HttpPut(uri); StringEntity entity = new StringEntity("string"); entity.setContentType("text/plain"); put.setEntity(entity);//from w w w . j a v a2 s . c o m CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpResponse response = httpclient.execute(put); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("c20string", EntityUtils.toString(response.getEntity())); } finally { httpclient.close(); } }
From source file:com.restfiddle.handler.http.PutHandler.java
public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException { RfResponseDTO response = null;/*from w w w .j a va 2 s.c om*/ CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(rfRequestDTO.getApiUrl()); httpPut.addHeader("Content-Type", "application/json"); httpPut.setEntity(new StringEntity(rfRequestDTO.getApiBody())); try { response = processHttpRequest(httpPut, httpclient); } finally { httpclient.close(); } return response; }
From source file:ranktracker.crawler.google.SeoKeywordDetail.java
public static String fetchSemrushPage(String urlsrc) throws IOException { System.out.println("---------------Without Proxy-----------------"); CloseableHttpClient httpclient = HttpClients.createDefault(); String responseBody = ""; try {/*from w w w.j av a 2 s . c o m*/ HttpGet httpget = new HttpGet(urlsrc); System.out.println("executing request " + httpget.getURI()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status <= 600) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; responseBody = httpclient.execute(httpget, responseHandler); return responseBody; } catch (Exception e) { System.out.println("Exception in getting the sourec code from website :" + e); } finally { try { httpclient.close(); } catch (Exception e) { System.out.println("Exception " + e); } } return responseBody; }
From source file:com.restfiddle.handler.http.PostHandler.java
public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException { RfResponseDTO response = null;// w w w .ja va 2 s . co m CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(rfRequestDTO.getApiUrl()); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(rfRequestDTO.getApiBody())); try { response = processHttpRequest(httpPost, httpclient); } finally { httpclient.close(); } return response; }
From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java
public static String doPost(String url, String json, String charset) { CloseableHttpClient httpClient = null; HttpPost httpPost = null;//from ww w .ja v a2 s . c om String result = null; try { httpClient = HttpClientFactory.getSSLClientFactory(); httpPost = new HttpPost(url); if (null != json) { StringEntity s = new StringEntity(json); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); // set contentType httpPost.setEntity(s); } CloseableHttpResponse response = httpClient.execute(httpPost); try { if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, charset); } } } catch (Exception e) { log.error("httpClient.execute(httpPost) is fail", e); } finally { if (response != null) { response.close(); } } } catch (Exception e) { log.error("doPost is fail ", e); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { } } } return result; }
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 w ww. jav a 2 s .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++; } 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.dtstack.jlogstash.distributed.http.cilent.HttpClient.java
public static String post(String url, Map<String, Object> bodyData) { String responseBody = null;//from w ww . j a v a2s. co m CloseableHttpClient httpClient = null; try { httpClient = getHttpClient(); HttpPost httPost = new HttpPost(url); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();// httPost.setConfig(requestConfig); } if (bodyData != null && bodyData.size() > 0) { httPost.setEntity(new StringEntity(objectMapper.writeValueAsString(bodyData))); } //? CloseableHttpResponse response = httpClient.execute(httPost); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); //FIXME ?header? responseBody = EntityUtils.toString(entity, Charsets.UTF_8); } else { logger.error("url:" + url + "--->http return status error:" + status); } } catch (Exception e) { logger.error("url:" + url + "--->http request error", e); } finally { try { if (httpClient != null) httpClient.close(); } catch (Exception e) { // TODO Auto-generated catch block logger.error(ExceptionUtil.getErrorMessage(e)); } } return responseBody; }