List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java
public String getEoAttrSNMP(String deviceIP, String attribute) { LOG.info("EmanSNMPBinding.getEoAttrSNMP: "); /* To do: generalize targetURL research using Java binding to make reference to 'local' ODL API *///from w ww .j av a2s . co m String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get"; String bodyString = buildSNMPGetBody(deviceIP, attribute); CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null; try { /* invoke ODL SNMP API */ HttpPost httpPost = new HttpPost(targetUrl); httpPost.addHeader("Authorization", "Basic " + encodedAuthStr); StringEntity inputBody = new StringEntity(bodyString); inputBody.setContentType(CONTENTTYPE_JSON); httpPost.setEntity(inputBody); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString()); InputStream in = responseEntity.getContent(); /* Parse response from ODL SNMP API */ JsonReader rdr = Json.createReader(in); JsonObject obj = rdr.readObject(); JsonObject output = obj.getJsonObject("output"); JsonArray results = output.getJsonArray("results"); JsonObject pwr = results.getJsonObject(0); String oid = pwr.getString("oid"); result = pwr.getString("value"); rdr.close(); LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result); } catch (Exception ex) { LOG.info("Error: " + ex.getMessage(), ex); } finally { try { httpClient.close(); } catch (IOException ex) { LOG.info("Error: " + ex.getMessage(), ex); } } return (result); }
From source file:com.bluehermit.apps.module.soap.client.HttpClientHelperImpl.java
public String post(String target, String message) throws Exception { String responeMessage = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*ww w. j av a 2s . c o m*/ HttpPost httppost = new HttpPost(target); httppost.setHeader("Content-Type", "text/xml"); httppost.setEntity(new StringEntity(message)); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { responeMessage = IOUtils.toString(instream, "UTF-8"); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } return responeMessage; }
From source file:com.adobe.aem.demo.communities.Loader.java
private static void doDelete(String hostname, String port, String url, String user, String password) { try {/*from w w w . j a v a 2 s.com*/ HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { // Adding the Basic Authentication data to the context for this command AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Composing the root URL for all subsequent requests String postUrl = "http://" + hostname + ":" + port + url; logger.debug("Deleting request as " + user + " with password " + password + " to " + postUrl); HttpDelete request = new HttpDelete(postUrl); httpClient.execute(target, request, localContext); } catch (Exception ex) { logger.error(ex.getMessage()); } finally { httpClient.close(); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:atc.otn.ckan.client.CKANClient.java
public JSONArray getExtent(String dTankDatasetURL) { CloseableHttpClient httpclient = HttpClients.createDefault(); ;//from w w w . jav a 2 s . c o m HttpGet httpGet; CloseableHttpResponse response = null; JSONArray extras = new JSONArray(); //************************ Action ************************* try { httpGet = new HttpGet(dTankDatasetURL + ".geojson"); httpGet.setHeader("Content-Type", "application/json"); httpGet.setHeader("Accept", "application/json"); //call the service response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { JSONObject jsonRespExtras; jsonRespExtras = new JSONObject(EntityUtils.toString(response.getEntity())); if (jsonRespExtras.has("bbox")) { extras = (JSONArray) jsonRespExtras.getJSONArray("bbox"); } } } catch (Exception e) { logger.error(e.getMessage()); } finally { if (response != null) { try { response.close(); httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); } } //end if } //end finally return extras; }
From source file:de.bytefish.fcmjava.client.http.HttpClient.java
private <TRequestMessage, TResponseMessage> TResponseMessage internalPost(TRequestMessage requestMessage, Class<TResponseMessage> responseType) throws Exception { CloseableHttpClient client = null; try {//from ww w .ja v a 2s.c o m client = httpClientBuilder.build(); // Initialize a new post Request: HttpPost httpPost = new HttpPost(settings.getFcmUrl()); // Get the JSON representation of the given request message: String requestJson = JsonUtils.getAsJsonString(requestMessage); // Set the JSON String as data: httpPost.setEntity(new StringEntity(requestJson, StandardCharsets.UTF_8)); // Execute the Request: CloseableHttpResponse response = null; try { response = client.execute(httpPost); // Get the HttpEntity of the Response: HttpEntity entity = response.getEntity(); // If we don't have a HttpEntity, we won't be able to convert it: if (entity == null) { // Simply return null (no response) in this case: return null; } // Get the JSON Body: String responseBody = EntityUtils.toString(entity); // Make Sure it is fully consumed: EntityUtils.consume(entity); // And finally return the Response Message: return JsonUtils.getEntityFromString(responseBody, responseType); } finally { if (response != null) { response.close(); } } } finally { if (client != null) { client.close(); } } }
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Helper method which posts the given json-string json to the given url * @param url/*from w w w .ja v a2 s .c om*/ * Exact url where the jsonData should get posted to * @param json * String of the JsonData which should be posted to the bulletin board * @param useTor * Boolean indicating if Json should be posted over Tor network * @return * retruns whether or not the data was sucessfully posted * @throws IOException IOException is thrown from the CloseableHttpClient */ public boolean postJsonStringToURL(String url, String json, Boolean useTor) throws IOException { boolean responseOK = true; boolean usingTor = useTor; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient httpClient = httpClientBuilder.create().build(); if (usingTor == true) { try { // Set Proxy System.setProperty("socksProxyHost", "127.0.0.1"); System.setProperty("socksProxyPort", "9050"); //prepare the post request HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(json); request.addHeader("content-type", "application/json"); request.setEntity(params); //sending post request and checking response CloseableHttpResponse response = httpClient.execute(request); //System.out.println(response); if (response.getStatusLine().getStatusCode() != 200) { responseOK = false; } response.close(); request.completed(); } catch (Exception ex) { responseOK = false; } finally { httpClient.close(); // 'Unset' the proxy. System.clearProperty("socksProxyHost"); } } else { try { //prepare the post request HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(json); request.addHeader("content-type", "application/json"); request.setEntity(params); //sending post request and checking response HttpResponse response = httpClient.execute(request); //System.out.println(response); if (response.getStatusLine().getStatusCode() != 200) { responseOK = false; } } catch (Exception ex) { responseOK = false; } finally { httpClient.close(); } } return responseOK; }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public String getFileId() throws IOException { logger.info("Querying file id of completed upload..."); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {/*from w w w . j a v a 2s . c om*/ httpclient = getHttpClient(); BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location); httpreq.addHeader("Authorization", auth.getAuthHeader()); httpreq.addHeader("Content-Length", "0"); httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString()); response = httpclient.execute(URIUtils.extractHost(uri), httpreq); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); String retSrc = EntityUtils.toString(entity); if (useOldApi) { // Old API will return XML! JSONObject result = XML.toJSONObject(retSrc); return result.getJSONObject("entry").getString("gd:resourceId").replace("file:", ""); } else { JSONObject result = new JSONObject(retSrc); return result.getString("id"); } } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:br.edu.ifrn.SuapClient.java
public String getData() { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//w ww . ja v a 2s . c om //Obtem as informaes bsicas do usurio logado no SUAP String url = "https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/"; HttpGet httpget = new HttpGet(url); httpget.addHeader("Accept", "application/json"); httpget.addHeader("X-CSRFToken", TOKEN); httpget.addHeader("Authorization", AUTH); System.out.println("Executing request " + httpget.getRequestLine()); // Create a custom response handler 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); } } }; String response = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); return response; } catch (IOException io) { System.out.println(io.getMessage()); } finally { try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ""; }
From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java
/** * Sends request without data and returns {@link ResponseContainer} object containing response's status code and body. * @param client HttpClient use to send request * @param request Http request object to be sent out * @return {@link ResponseContainer} with response data * @throws IOException When there's an error sending out request *//*from w w w .ja v a 2 s .c o m*/ private ResponseContainer sendRequest(CloseableHttpClient client, Object request) throws IOException { ResponseContainer responseContainer = null; try { HttpResponse response = null; LOGGER.info("Sending request to " + mUrl); if (request instanceof HttpEntityEnclosingRequestBase) { response = client.execute((HttpEntityEnclosingRequestBase) request); } else { response = client.execute((HttpUriRequest) request); } int responseCode = response.getStatusLine().getStatusCode(); String responseText = EntityUtils.toString(response.getEntity()); Header[] headers = response.getAllHeaders(); String responseLog = "Response: " + responseCode + " - "; if (responseText != null) responseLog += responseText; if (responseCode == ServerStatusCodes.OK) { LOGGER.info(responseLog); } else { LOGGER.error(responseLog); } responseContainer = new ResponseContainer(responseCode, responseText, headers); } catch (IOException e) { throw new IOException("Connection failed. Request not sent"); } finally { client.close(); } return responseContainer; }
From source file:org.asqatasun.util.http.HttpRequestHandler.java
public int getHttpStatus(String url) throws IOException { String encodedUrl = getEncodedUrl(url); CloseableHttpClient httpClient = getHttpClient(encodedUrl); HttpHead head = new HttpHead(encodedUrl); try {/*from w w w.j a v a2 s . c om*/ LOGGER.debug("executing head request to retrieve page status on " + head.getURI()); HttpResponse response = httpClient.execute(head); if (LOGGER.isDebugEnabled()) { LOGGER.debug("received " + response.getStatusLine().getStatusCode() + " from head request"); for (Header h : head.getAllHeaders()) { LOGGER.debug("header : " + h.getName() + " " + h.getValue()); } } return response.getStatusLine().getStatusCode(); } catch (UnknownHostException uhe) { LOGGER.warn("UnknownHostException on " + encodedUrl); return HttpStatus.SC_NOT_FOUND; } catch (IllegalArgumentException iae) { LOGGER.warn("IllegalArgumentException on " + encodedUrl); return HttpStatus.SC_NOT_FOUND; } catch (IOException ioe) { LOGGER.warn("IOException on " + encodedUrl); return HttpStatus.SC_NOT_FOUND; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources head.releaseConnection(); httpClient.close(); } }