List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:eionet.gdem.utils.HttpUtils.java
/** * Downloads remote file//from w ww . j a v a 2 s. c om * @param url URL * @return Downloaded file * @throws DCMException If an error occurs. * @throws IOException If an error occurs. */ public static byte[] downloadRemoteFile(String url) throws DCMException, IOException { byte[] responseBody = null; CloseableHttpClient client = HttpClients.createDefault(); // Create a method instance. HttpGet method = new HttpGet(url); // Execute the method. CloseableHttpResponse response = null; try { response = client.execute(method); HttpEntity entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase()); throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR, response.getStatusLine().getReasonPhrase()); } // Read the response body. InputStream instream = entity.getContent(); responseBody = IOUtils.toByteArray(instream); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data // System.out.println(new String(responseBody)); /*catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); throw e;*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw e; } finally { // Release the connection. response.close(); method.releaseConnection(); client.close(); } return responseBody; }
From source file:httpServerClient.app.QuickStart.java
public static void getAllMessages(String[] args) throws Exception { // arguments to run Quick start: // args[0] GET // args[1] IPAddress of server // args[2] port No. CloseableHttpClient httpclient = HttpClients.createDefault(); JacksonObjectMapperToList myList = new JacksonObjectMapperToList(); try {//from w ww . java 2s . c o m HttpGet httpGet = new HttpGet("http://" + args[1] + ":" + args[2] + "/getAllMessages"); 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 entity1 = response1.getEntity(); String result = EntityUtils.toString(entity1); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ //myList.jsonToList(result); myList.jacksonToList(result); myList.PrintList(); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:org.keycloak.testsuite.OAuthClient.java
public void closeClient(CloseableHttpClient client) { try {//from w w w.j a v a2 s. co m client.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java
/** * Deletes the specified ranker/*from www . j a v a 2 s. c o m*/ * * @param ranker_id ofthe ranker to be deleted * @throws ClientProtocolException * @throws IOException * @throws JSONException */ public static void deleteRanker(CloseableHttpClient client, String ranker_id) throws ClientProtocolException, IOException { JSONObject res; try { HttpDelete httpdelete = new HttpDelete(ranker_url + "/" + ranker_id); httpdelete.setHeader("Content-Type", "application/json"); CloseableHttpResponse response = client.execute(httpdelete); try { String result = EntityUtils.toString(response.getEntity()); res = (JSONObject) JSON.parse(result); if (res.isEmpty()) { logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE"), //$NON-NLS-1$ ranker_id)); } else { logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE_FAIL"), //$NON-NLS-1$ ranker_id)); } } catch (NullPointerException | JSONException e) { logger.error(e.getMessage()); } finally { response.close(); } } finally { client.close(); } }
From source file:httpServerClient.app.QuickStart.java
public static void sendMessage(String[] args) throws Exception { // arguments to run Quick start POST: // args[0] POST // args[1] IPAddress of server // args[2] port No. // args[3] user name // args[4] myMessage CloseableHttpClient httpclient = HttpClients.createDefault(); try {/* w w w .ja v a2 s . c o m*/ HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage"); // httpPost.setEntity(new StringEntity("lubo je kral")); httpPost.setEntity( new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}")); CloseableHttpResponse response1 = httpclient.execute(httpPost); // 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 entity1 = response1.getEntity(); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:com.kingmed.dp.ndp.impl.SignOutResponseHandlerTest.java
@Test public void testSignOut() { for (NDPServe ndpServe : allNDPServes) { String signinUrl = ndpServe.getUrlSignin(); String signOutUrl = ndpServe.getUrlSignout(); CloseableHttpClient httpclient = HttpClients.createDefault(); NDPServeResponseHandler responeHandler = new SignInResponseHandler(); String cookie = null;/*from w w w. j a va 2s .c om*/ try { HttpGet httpget = new HttpGet(signinUrl); httpclient.execute(httpget, responeHandler); cookie = responeHandler.getCookie(); Assert.notNull(cookie); } catch (Exception e) { e.printStackTrace(); fail("?"); } finally { try { httpclient.close(); } catch (IOException ex) { fail(""); } } Header header = new BasicHeader("Cookie", cookie); httpclient = HttpClients.createDefault(); responeHandler = new SignOutResponseHandler(); try { HttpGet httpget = new HttpGet(signOutUrl); httpget.setHeader(header.getName(), header.getValue()); String status = httpclient.execute(httpget, responeHandler); assertTrue("?", NDPServeImpl.STATUS_SUCCEEDED.equals(status)); } catch (Exception e) { e.printStackTrace(); fail(""); } finally { try { httpclient.close(); } catch (IOException ex) { fail(""); } } } }
From source file:jenkins.plugins.logstash.persistence.ElasticSearchDao.java
@Override public void push(String data) throws IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpPost post = getHttpPost(data);/* w w w . j av a2 s . c o m*/ try { httpClient = clientBuilder.build(); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != 201) { throw new IOException(this.getErrorMessage(response)); } } finally { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } }
From source file:siddur.solidtrust.image.ImageController.java
@Transactional(readOnly = false) @RequestMapping(value = "/image/save") public @ResponseBody String save(@RequestParam(value = "index") int index, @RequestParam(value = "imageProductId") int imageProductId, @RequestParam(value = "url", required = false) String url, @RequestParam(value = "file", required = false) MultipartFile file, Model model) throws Exception { ImageInfo image = null;/* w w w.j a va 2s . co m*/ if (!StringUtils.isEmpty(url)) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { image = extractor.persist(url, httpclient); } finally { httpclient.close(); } } else if (file != null) { image = extractor.persist(file); } if (image != null) { String filename = image.getUuid(); ImageProduct ip = em.find(ImageProduct.class, imageProductId); setImage(ip, filename, index); em.persist(ip); return filename; } return ""; }
From source file:com.kingmed.dp.ndp.impl.UpdateLinkedFolderResponseHandlerTest.java
@Test public void testUpdateLinkedFolder() { for (NDPServe ndpServe : allNDPServes) { String signinUrl = ndpServe.getUrlSignin(); CloseableHttpClient httpclient = HttpClients.createDefault(); NDPServeResponseHandler responeHandler = new SignInResponseHandler(); String cookie = null;/*w ww. j a v a2 s. co m*/ try { HttpGet httpget = new HttpGet(signinUrl); httpclient.execute(httpget, responeHandler); cookie = responeHandler.getCookie(); Assert.notNull(cookie); } catch (Exception e) { e.printStackTrace(); fail("?"); } finally { try { httpclient.close(); } catch (IOException ex) { fail(""); } } String uri = ndpServe.getUrlForUpdateLinkedFolders(); httpclient = HttpClients.createDefault(); responeHandler = new UpdateLinkedFoldersResponseHandler(); try { HttpGet httpget = new HttpGet(uri); httpget.setHeader("Cookie", cookie); String status = httpclient.execute(httpget, responeHandler); System.out.println("status==================" + status); assertTrue("?succeed", status.equals(NDPServeImpl.STATUS_SUCCEEDED)); } catch (Exception e) { e.printStackTrace(); fail(""); } finally { try { httpclient.close(); } catch (IOException ex) { fail(""); } } } }
From source file:com.glaf.core.util.http.HttpClientUtils.java
/** * ??POST/*ww w . j ava 2 s.c o m*/ * * @param url * ?? * @param encoding * * @param dataMap * ? * * @return */ public static String doPost(String url, String encoding, Map<String, String> dataMap) { StringBuffer buffer = new StringBuffer(); HttpPost post = null; InputStreamReader is = null; BufferedReader reader = null; BasicCookieStore cookieStore = new BasicCookieStore(); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build(); try { post = new HttpPost(url); if (dataMap != null && !dataMap.isEmpty()) { List<org.apache.http.NameValuePair> nameValues = new ArrayList<org.apache.http.NameValuePair>(); for (Map.Entry<String, String> entry : dataMap.entrySet()) { String name = entry.getKey().toString(); String value = entry.getValue(); nameValues.add(new BasicNameValuePair(name, value)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValues, encoding); post.setEntity(entity); } HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); is = new InputStreamReader(entity.getContent(), encoding); reader = new BufferedReader(is); String tmp = reader.readLine(); while (tmp != null) { buffer.append(tmp); tmp = reader.readLine(); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { IOUtils.closeStream(reader); IOUtils.closeStream(is); if (post != null) { post.releaseConnection(); } try { client.close(); } catch (IOException ex) { } } return buffer.toString(); }