List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:com.conwet.wirecloud.ide.WirecloudAPI.java
public void deployWGT(File wgtFile, String token) throws IOException, FailureResponseException { URL url;// w w w .j a v a 2 s .c o m try { url = new URL(this.url, RESOURCE_COLLECTION_PATH); } catch (MalformedURLException e) { throw new AssertionError(e); } HttpPost request = new HttpPost(url.toString()); request.setHeader("Authorization", "Bearer " + token); request.setHeader("Accept", "application/json"); request.setHeader("Content-Type", "application/octet-stream"); request.setEntity(new FileEntity(wgtFile)); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try { httpclient = createHttpClient(url); response = httpclient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 201: break; case 400: case 401: try { throw FailureResponseException .createFailureException(EntityUtils.toString(response.getEntity())); } catch (JSONException e) { throw new UnexpectedResponseException(); } default: throw new UnexpectedResponseException(); } } finally { httpclient.close(); if (response != null) { response.close(); } } }
From source file:com.floragunn.searchguard.AbstractUnitTest.java
protected String executeSimpleRequest(final String request) throws Exception { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try {/*w w w .j a va2 s . c o m*/ httpClient = getHTTPClient(); response = httpClient.execute(new HttpGet(getHttpServerUri() + "/" + request)); if (response.getStatusLine().getStatusCode() >= 300) { throw new Exception("Statuscode " + response.getStatusLine().getStatusCode()); } return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); } finally { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSignOut(CloseableHttpClient httpClient, String url, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { try {/*w ww . j a v a 2 s. c om*/ // logout to service provider HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String parsedEntity = EntityUtils.toString(entity); Assert.assertTrue(parsedEntity.contains("Logout from the following realms")); Source source = new Source(parsedEntity); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } // Now send logout form to IdP nvps.add(new BasicNameValuePair("_eventId_submit", "Logout")); HttpPost httppost = new HttpPost("https://localhost:" + idpPort + "/" + postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); return EntityUtils.toString(entity); } finally { if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.hive.service.server.TestHS2HttpServer.java
@Test public void testConfStrippedFromWebUI() throws Exception { String pwdValFound = null; String pwdKeyFound = null;/*from w w w . j a va 2 s. c om*/ CloseableHttpClient httpclient = null; try { httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:" + webUIPort + "/conf"); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { HttpEntity entity1 = response1.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent())); String line; while ((line = br.readLine()) != null) { if (line.contains(metastorePasswd)) { pwdValFound = line; } if (line.contains(ConfVars.METASTOREPWD.varname)) { pwdKeyFound = line; } } EntityUtils.consume(entity1); } finally { response1.close(); } } finally { if (httpclient != null) { httpclient.close(); } } assertNotNull(pwdKeyFound); assertNull(pwdValFound); }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get./*w w w . jav a2 s . c om*/ * * @param uri * the uri * @param headers * the headers * @return the string * @throws Exception * the exception */ public static String doGet(URI uri, HashMap<String, String> headers) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String respString = null; try { /* * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs. * * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q", * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build(); */ HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity = response1.getEntity(); // do something useful with the response body if (entity != null) { respString = EntityUtils.toString(entity); } // and ensure it is fully consumed EntityUtils.consume(entity); } finally { response1.close(); } } finally { httpclient.close(); } return respString; }
From source file:es.uned.dia.jcsombria.softwarelinks.transport.HttpTransport.java
public Object send(String request) throws Exception { Object response = null;/* w w w. j ava2s.c om*/ CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverURL.toString()); httppost.setEntity(new StringEntity(request)); // 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 < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httppost, responseHandler); response = responseBody; } finally { httpclient.close(); } return response; }
From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java
public String setEoAttrSNMP(String deviceIP, String attribute, String value) { /* To do: generalize targetURL */ String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-set"; String bodyString = buildSNMPSetBody(deviceIP, attribute, value); CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null;//w ww. j a v a2s. com LOG.info("EmanSNMPBinding.setEoAttrSNMP: HTTP SET SNMP call to: " + targetUrl); try { 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("Response Status: " + httpResponse.getStatusLine().toString()); InputStream in = responseEntity.getContent(); } 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:eu.diacron.crawlservice.app.Util.java
public static String getCrawlid(URL urltoCrawl) { String crawlid = ""; System.out.println("start crawling page"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/*from www .jav a 2 s. c o m*/ //HttpPost httppost = new HttpPost("http://diachron.hanzoarchives.com/crawl"); HttpPost httppost = new HttpPost(Configuration.REMOTE_CRAWLER_URL_CRAWL_INIT); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("name", UUID.randomUUID().toString())); urlParameters.add(new BasicNameValuePair("scope", "page")); urlParameters.add(new BasicNameValuePair("seed", urltoCrawl.toString())); httppost.setEntity(new UrlEncodedFormEntity(urlParameters)); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { crawlid = inputLine; } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return crawlid; }
From source file:com.alibaba.jstorm.daemon.nimbus.metric.uploader.AlimonitorClient.java
private boolean httpPost(String url, String msg) { boolean ret = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {//from w w w. j a v a 2 s. c o m HttpPost request = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("name", monitorName)); nvps.add(new BasicNameValuePair("msg", msg)); request.setEntity(new UrlEncodedFormEntity(nvps)); response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { LOG.info(EntityUtils.toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("Exception when sending http request to ali monitor", e); } finally { try { if (response != null) response.close(); httpClient.close(); } catch (Exception e) { LOG.error("Exception when closing httpclient", e); } } return ret; }
From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.java
protected String executeSimpleRequest(final String request) throws Exception { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try {/*w ww.jav a 2 s. co m*/ httpClient = getHTTPClient(); response = httpClient.execute(new HttpGet(getHttpServerUri() + "/" + request)); if (response.getStatusLine().getStatusCode() >= 300) { throw new Exception("Statuscode " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase() + "-" + IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8)); } return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); } finally { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } }