List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.dasein.cloud.utils.requester.DaseinParallelRequestExecutor.java
public List<T> execute() throws DaseinRequestException { final HttpClientBuilder clientBuilder = setProxyIfRequired(httpClientBuilder); final CloseableHttpClient httpClient = clientBuilder.build(); List<T> results = new ArrayList<T>(); List<Callable<T>> tasks = new ArrayList<Callable<T>>(); for (final HttpUriRequest httpUriRequest : httpUriRequests) { tasks.add(new Callable<T>() { @Override/*from w w w . jav a 2 s. co m*/ public T call() throws Exception { return execute(httpClient, httpUriRequest); } }); } try { try { ExecutorService executorService = Executors.newFixedThreadPool(httpUriRequests.size()); List<Future<T>> futures = executorService.invokeAll(tasks); for (Future<T> future : futures) { T result = future.get(); results.add(result); } return results; } finally { httpClient.close(); } } catch (Exception e) { throw new DaseinRequestException(e.getMessage(), e); } }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, HttpEntity entity, HashMap<String, String> headers) { HttpPost post = null;//w w w.j a va 2s .c o m HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); post = new HttpPost(url); post.setEntity(entity); for (String key : headers.keySet()) { post.setHeader(key, headers.get(key)); } post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public String doGet(String url, Map<String, String> params) throws Exception { RequestBuilder _request = RequestBuilder.get().setUri(url); for (Map.Entry<String, String> entry : params.entrySet()) { _request.addParameter(entry.getKey(), entry.getValue()); }/*from w w w .jav a 2s .com*/ CloseableHttpClient _httpClient = __doBuildHttpClient(); try { _LOG.debug("Request URL [" + url + "], Param [" + params + "]"); String _result = _httpClient.execute(_request.build(), new ResponseHandler<String>() { public String handleResponse(HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET); } }); _LOG.debug("Request URL [" + url + "] Response [" + _result + "]"); return _result; } finally { _httpClient.close(); } }
From source file:org.alfresco.tutorials.webscripts.HelloWorldWebScriptIT.java
@Test public void testWebScriptCall() throws Exception { String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld"; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 8080), new UsernamePasswordCredentials(ALFRESCO_USERNAME, ALFRESCO_PWD)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from w w w . j a va 2 s. co m HttpGet httpget = new HttpGet(webscriptURL); HttpResponse httpResponse = httpclient.execute(httpget); assertEquals("HTTP Response Status is not OK(200)", HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode()); HttpEntity entity = httpResponse.getEntity(); assertNotNull("Response from Web Script is null", entity); String response = EntityUtils.toString(entity); JSONParser parser = new JSONParser(); JSONObject jsonResponseObj = (JSONObject) parser.parse(response); assertTrue("Folder not found", (boolean) jsonResponseObj.get("foundFolder")); assertTrue("Doc not found", (boolean) jsonResponseObj.get("foundDoc")); } finally { httpclient.close(); } }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse sendHTTPPost(String url, String payload, HashMap<String, String> headers) { HttpPost post = null;//from w ww . jav a 2s . c o m HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8); post = new HttpPost(url); post.setEntity(requestEntity); for (String key : headers.keySet()) { post.setHeader(key, headers.get(key)); } response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:org.pepstock.jem.commands.util.HttpUtil.java
/** * Calls a http node of JEM to get group anme of Hazelcast cluster, * necessary to client to connect to JEM. * //from w ww.j a va 2s.co m * @param url http URL to call * @return group name of Hazelcast cluster * @throws SubmitException if errors occur */ public static String getGroupName(String url) throws SubmitException { // creates a HTTP client CloseableHttpClient httpclient = null; try { httpclient = createHttpClient(url); // concats URL with query string String completeUrl = url + HttpUtil.NAME_QUERY_STRING; // prepares GET request and basic response handler HttpGet httpget = new HttpGet(completeUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // executes and no parsing // result must be only a string String responseBody = httpclient.execute(httpget, responseHandler); return responseBody.trim(); } catch (KeyManagementException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (UnrecoverableKeyException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (NoSuchAlgorithmException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (KeyStoreException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (URISyntaxException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (ClientProtocolException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } catch (IOException e) { throw new SubmitException(SubmitMessage.JEMW002E, e); } finally { // close http client if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LogAppl.getInstance().ignore(e.getMessage(), e); } } } }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
@Override public Set<String> getMeasurementsLike(String dbName, String partialMeasurementName) throws IOException { List<String> proxies = new ArrayList<>(); dbName = decodeDbAndProxyNames(proxies, dbName); if (proxies.size() > 0) { return local.getMeasurementsLike(dbName, partialMeasurementName); } else {/*from w w w .j a v a2s . c o m*/ Set<String> localResult = local.getMeasurementsLike(dbName, partialMeasurementName); for (Entry<Integer, WorkerEntry> entry : columbus.getWorkerMap().entrySet()) { if (entry.getKey() != columbus.getSelfWorkerId()) { String newDbName = encodeDbAndProxyName(dbName, String.valueOf(columbus.getSelfWorkerId())); // http call CloseableHttpClient client = Utils.getClient( "http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/", 5000, 5000); // Grafana API HttpPost post = new HttpPost("http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/" + newDbName + "/query/search"); CloseableHttpResponse result = client.execute(post); if (result.getStatusLine().getStatusCode() == 200) { result.close(); client.close(); Gson gson = new Gson(); @SuppressWarnings("unchecked") Set<String> fromJson = gson.fromJson(EntityUtils.toString(result.getEntity()), Set.class); localResult.addAll(fromJson); } } } return localResult; } }
From source file:ApkItem.java
public void uploadFile() { try {//from www. ja v a2s. com CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://192.168.1.130:8080/imooc/"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); CountingMultipartRequestEntity.ProgressListener pListener = new CountingMultipartRequestEntity.ProgressListener() { @Override public void progress(float percentage) { apkState.setProcess((int) percentage); firePropertyChange("uploadProcess", -1, percentage); } }; httpPost.setEntity(new CountingMultipartRequestEntity.ProgressEntityWrapper(multipart, pListener)); CloseableHttpResponse response = client.execute(httpPost); client.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java
/** * Returns the status of the specified ranker * /*from w w w . j a va 2 s.c o m*/ * @param client {@link CloseableHttpClient} object with credentials * @param ranker_url URL to the ranker. Ex.) * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/ rankers/{ranker_id} * @return status. Ex.) "Available", "Training", "Failed" * @throws IOException */ public String getRankerStatus(CloseableHttpClient client, String ranker_url) throws IOException { String status = null; JSONObject res; try { HttpGet httpget = new HttpGet(ranker_url); CloseableHttpResponse response = client.execute(httpget); try { String result = EntityUtils.toString(response.getEntity()); res = new JSONObject(result); status = res.getString("status"); } catch (JSONException e) { throw new RuntimeException("JSON Exception!", e); } finally { response.close(); } } finally { client.close(); } return status; }