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 JSONObject obtainMashableComponents() throws IOException, UnexpectedResponseException { URL url;/*from ww w. j ava2 s . c om*/ try { url = new URL(this.url, RESOURCE_COLLECTION_PATH); } catch (MalformedURLException e) { throw new AssertionError(e); } HttpGet request = new HttpGet(url.toString()); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try { httpclient = createHttpClient(url); request.setHeader("Authorization", "Bearer " + token); request.setHeader("Accept", "application/json"); response = httpclient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new UnexpectedResponseException(); } try { return new JSONObject(EntityUtils.toString(response.getEntity())); } catch (JSONException e) { throw new UnexpectedResponseException(); } } finally { httpclient.close(); if (response != null) { response.close(); } } }
From source file:org.keycloak.test.FluentTestsHelper.java
/** * Checks if given endpoint returns successfully with supplied token. * * @param endpoint Endpoint to be evaluated, * @param token Token that will be passed into the <code>Authorization</code> header. * @return <code>true</code> if the endpoint returns forbidden. * @throws IOException Thrown by the underlying HTTP Client implementation *///from www . j a va 2 s . c o m public boolean testGetWithAuth(String endpoint, String token) throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); try { HttpGet get = new HttpGet(keycloakBaseUrl + endpoint); get.addHeader("Authorization", "Bearer " + token); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { return false; } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return true; } finally { is.close(); } } finally { client.close(); } }
From source file:org.wso2.security.tools.scanner.dependency.js.ticketcreator.JIRARestClient.java
/** * Invoke put method to attach file for particular ticket. * * @param auth credentials info of JIRA. * @param url url to be invoked./*w w w .j av a 2s . c o m*/ * @param path path of the file to be attached. * @throws TicketCreatorException Exception occurred while attaching the file with ticket. */ public void invokePutMethodWithFile(String auth, String url, String path) throws TicketCreatorException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); httppost.setHeader("X-Atlassian-Token", "nocheck"); httppost.setHeader("Authorization", "Basic " + auth); File fileToUpload = new File(path); FileBody fileBody = new FileBody(fileToUpload); HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build(); httppost.setEntity(entity); CloseableHttpResponse response; try { response = httpclient.execute(httppost); log.info("[JS_SEC_DAILY_SCAN] File attached with ticket : " + response.toString()); } catch (IOException e) { throw new TicketCreatorException( "File upload failed while attaching the scan report with issue ticket: " + path, e); } finally { try { httpclient.close(); } catch (IOException e) { log.error("Exception occurred while closing the http connection", e); } } }
From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java
protected byte[] execute(HttpUriRequest request) throws IOException { Log.w(TAG, "connecting to " + apn.getMmsc()); CloseableHttpClient client = null; CloseableHttpResponse response = null; try {/*from w w w.j a v a 2s . c o m*/ client = constructHttpClient(); response = client.execute(request); Log.w(TAG, "* response code: " + response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { return parseResponse(response.getEntity().getContent()); } } catch (NullPointerException npe) { // TODO determine root cause // see: https://github.com/WhisperSystems/Signal-Android/issues/4379 throw new IOException(npe); } finally { if (response != null) response.close(); if (client != null) client.close(); } throw new IOException("unhandled response code"); }
From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java
public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception { CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build(); int responseCode = 0; StringBuffer respo = null;//from w w w .j a v a 2 s .co m String userPassword = username + ":" + pwd; // String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes()); String encoding = Base64.encodeBase64String(userPassword.getBytes()); try { HttpPost request = new HttpPost(url); request.addHeader("Authorization", "Basic " + encoding); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept-Language", "en-US,en;q=0.5"); request.addHeader("Content-Type", "application/json; charset=UTF-8"); request.setHeader("Accept", "application/json"); System.out.println("Executing request " + request.getRequestLine()); System.out.println("Executing request " + Arrays.toString(request.getAllHeaders())); StringEntity se = new StringEntity(body); request.setEntity(se); CloseableHttpResponse response = client.execute(request); try { responseCode = response.getStatusLine().getStatusCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post body : " + body); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); respo = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { respo.append(inputLine); } } finally { response.close(); } } finally { client.close(); } HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString())); System.out.println(result.getStatusCode() + "/n" + result.getBody()); return result; }
From source file:counsil.WebClient.java
public String getFromURL(String ip, int port, String URL) throws IOException { String outString = ""; Integer portInt = port;/* w ww .j a v a 2 s. c o m*/ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2 * 1000).build(); CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); BasicConfigurator.configure(); try { HttpGet httpget = new HttpGet("http://" + ip + ":" + portInt.toString() + URL); // Create a custom response handler ResponseHandler<String> responseHandler = (HttpResponse response) -> { 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(httpget, responseHandler); outString = responseBody; } finally { httpclient.close(); } return outString; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse get(String url, Map<String, String> params, Charset charset, Header[] headers, final String defaultResponseCharset) throws Exception { RequestBuilder _request = RequestBuilder.get().setUri(url).setCharset(charset); for (Map.Entry<String, String> entry : params.entrySet()) { _request.addParameter(entry.getKey(), entry.getValue()); }//w w w .j av a 2 s .c o m if (headers != null && headers.length > 0) { for (Header _header : headers) { _request.addHeader(_header); } } CloseableHttpClient _httpClient = __doBuildHttpClient(); try { return _httpClient.execute(_request.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java
@Test public void noFileParameterTest() throws URISyntaxException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL fileUrl = loader.getResource(INPUT_FILENAME); File inputFile = new File(fileUrl.toURI()); assertNotNull(inputFile);//from ww w . j a v a 2s . c o m assertTrue(inputFile.exists()); assertTrue(inputFile.isFile()); assertTrue(inputFile.canRead()); CloseableHttpClient httpclient = HttpClients.createDefault(); String url = LOCAL_TOMCAT_SERVICE_URL; HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null; try { logger.debug("executing request " + httpGet.getRequestLine()); response = httpclient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); logger.debug("Response status line : " + statusLine); assertEquals(400, statusLine.getStatusCode()); } catch (IOException e) { logger.error("Something went wrong...", e); fail(e.getMessage()); } finally { if (response != null) { try { response.close(); httpclient.close(); } catch (IOException e) { // nothing to do ; } } } logger.debug("DONE"); }
From source file:org.sasabus.export2Freegis.network.SubscriptionManager.java
public boolean subscribe() throws IOException { for (int i = 0; i < SUBFILEARRAY.length; ++i) { Scanner sc = new Scanner(new File(SUBFILEARRAY[i])); String subscriptionstring = ""; while (sc.hasNextLine()) { subscriptionstring += sc.nextLine(); }//from w ww . ja v a 2 s. c o m sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DATE, 1); d = c.getTime(); String valid_until = date_date.format(d) + "T" + date_time.format(d); valid_until = valid_until.substring(0, valid_until.length() - 2) + ":" + valid_until.substring(valid_until.length() - 2); subscriptionstring = subscriptionstring.replaceAll(":timestamp_valid", valid_until); subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp); String requestString = "http://" + this.address + ":" + this.portnumber_sender + "/TmEvNotificationService/gms/subscription.xml"; HttpPost subrequest = new HttpPost(requestString); StringEntity requestEntity = new StringEntity(subscriptionstring, ContentType.create("text/xml", "ISO-8859-1")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(subrequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { try { System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode()); System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase()); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responsebody = EntityUtils.toString(responseEntity); System.out.println(responsebody); } } finally { response.close(); httpClient.close(); } return false; } System.out.println("Subscription of " + SUBFILEARRAY[i]); } return true; }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
@Override public boolean checkIfExists(String dbName) throws Exception { List<String> proxies = new ArrayList<>(); dbName = decodeDbAndProxyNames(proxies, dbName); if (proxies.size() > 0) { return local.checkIfExists(dbName); } else {//from w w w . j a va 2s . c o m boolean localResult = local.checkIfExists(dbName); 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); // Grafan API HttpGet post = new HttpGet("http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/" + newDbName + "/hc"); CloseableHttpResponse result = client.execute(post); if (result.getStatusLine().getStatusCode() == 200) { localResult = true; result.close(); client.close(); break; } } } return localResult; } }