List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java
/** * {@inheritDoc}//from w ww.jav a 2 s .co m */ @Override public List<Application> getApplications(String apiKey) throws IOException { List<Application> result = new ArrayList<Application>(); URI url = null; try { url = new URI(API_URL + APPLICATIONS_ENDPOINT); } catch (URISyntaxException e) { // no need to handle this } HttpGet request = new HttpGet(url); setHeaders(request, apiKey); CloseableHttpClient client = getHttpClient(url); ResponseHandler<ApplicationList> rh = new ResponseHandler<ApplicationList>() { @Override public ApplicationList handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } Gson gson = new GsonBuilder().create(); Reader reader = new InputStreamReader(entity.getContent()); return gson.fromJson(reader, ApplicationList.class); } }; try { ApplicationList response = client.execute(request, rh); result.addAll(response.getApplications()); } finally { client.close(); } return result; }
From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java
protected void testHttpClientWithResponseHandler(HttpUriRequest request, boolean fault) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*w ww. ja v a2s . c o m*/ request.addHeader("test-header", "test-value"); if (fault) { request.addHeader("test-fault", "true"); } // 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(); assertEquals("Unexpected response code", 200, status); HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } }; String responseBody = httpclient.execute(request, responseHandler); assertEquals(HELLO_WORLD, responseBody); } catch (ConnectException ce) { assertEquals(BAD_URL, request.getURI().toString()); } finally { httpclient.close(); } Wait.until(() -> getTracer().finishedSpans().size() == 1); List<MockSpan> spans = getTracer().finishedSpans(); assertEquals(1, spans.size()); assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey())); assertEquals(request.getMethod(), spans.get(0).operationName()); assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey())); if (fault) { assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey())); } }
From source file:org.alfresco.cacheserver.http.CacheHttpClient.java
public void getNodeById(String hostname, int port, String username, String password, String nodeId, String nodeVersion, HttpCallback callback) throws IOException { HttpHost target = new HttpHost(hostname, port, "http"); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth);// w w w . j a va2s . com // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); CloseableHttpClient httpClient = getHttpClient(target, localContext, username, password); try { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000) .build(); String uri = "http://" + hostname + ":" + port + "/alfresco/api/-default-/private/alfresco/versions/1/contentByNodeId/" + nodeId + "/" + nodeVersion; HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Content-Type", "text/plain"); httpGet.setConfig(requestConfig); System.out.println("Executing request " + httpGet.getRequestLine()); CloseableHttpResponse response = httpClient.execute(target, httpGet, localContext); try { callback.execute(response.getEntity().getContent()); // EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpClient.close(); } }
From source file:com.lenovo.h2000.services.LicenseServiceImpl.java
@Override public String upload(byte[] fileBytes, Map<String, String> headers) throws Exception { Map<String, String> params = new HashMap<String, String>(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost( HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params)); String responseBody = ""; DataInputStream in = null;//ww w . jav a2 s. com try { ByteArrayEntity requestEntity = new ByteArrayEntity(fileBytes); requestEntity.setContentEncoding("UTF-8"); requestEntity.setContentType("application/octet-stream"); httpPost.setEntity(requestEntity); HttpResponse response = httpClient.execute(httpPost); response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); HttpEntity responseEntity = response.getEntity(); responseBody = EntityUtils.toString(responseEntity); } catch (ClientProtocolException e) { e.printStackTrace(); _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage()); } finally { httpClient.close(); if (in != null) { in.close(); } } return responseBody; }
From source file:com.linkedin.drelephant.exceptions.azkaban.AzkabanWorkflowClient.java
/** * @param username The username of the user * @return Encoded password of the user//from w w w .j a va 2s .co m * @throws IOException private String getHeadlessChallenge(String username) throws IOException { */ private String getHeadlessChallenge(String username) throws IOException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead String encodedPassword = null; try { String userUrl = _azkabanUrl + "/restli/liuser?action=headlessChallenge"; HttpPost request = new HttpPost(userUrl); StringEntity params = new StringEntity("{\"username\":\"" + username + "\"}"); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); String responseString = EntityUtils.toString(response.getEntity()); JSONObject jobject = new JSONObject(responseString); encodedPassword = jobject.getString("value"); } catch (Exception ex) { throw new RuntimeException("Unexpected exception in decoding headless account " + ex.toString()); } finally { httpClient.close(); return encodedPassword; } }
From source file:jchat.test.RestTest.java
@Test public void test() throws Exception { eao.withQuery("DELETE FROM " + MessageEntity.class.getName(), new BaseEAO.ExecutableQuery<Integer>() { @Override// ww w . j a va2 s . com public Integer execute(Query query) { return query.executeUpdate(); } }); CloseableHttpClient client = HttpClients.custom().build(); // If this fails, don't forget to change you JS code Assert.assertEquals("{\"messageDto\":[]}", getBody(client.execute(new HttpGet(deploymentURL.toURI() + "rest/messages")))); String text = "Hi there! [" + System.currentTimeMillis() + "]"; try { // login post(client, "rest/auth", new BasicNameValuePair("user", "bototaxi")); // post message post(client, "rest/messages", new BasicNameValuePair("message", text)); int tryCounter = 0; while (true) { String json = getBody(client.execute(new HttpGet(deploymentURL.toURI() + "rest/messages"))); if (json.contains(text)) { break; } if (++tryCounter > 10) { Assert.fail("We tried " + tryCounter + " times without success. message: [" + text + "]; JSON: [" + json + "]"); } // Not time enough to process the message. Try it again! Thread.sleep(500); } } finally { client.close(); } }
From source file:com.okta.tools.awscli.java
private static String awsSamlHandler(String oktaSessionToken) throws ClientProtocolException, IOException { HttpGet httpget = null;/*w w w . ja v a 2s .c o m*/ CloseableHttpResponse responseSAML = null; CloseableHttpClient httpClient = HttpClients.createDefault(); String resultSAML = ""; String outputSAML = ""; // Part 2: Get the Identity Provider and Role ARNs. // Request for AWS SAML response containing roles httpget = new HttpGet(oktaAWSAppURL + "?onetimetoken=" + oktaSessionToken); responseSAML = httpClient.execute(httpget); samlFailHandler(responseSAML.getStatusLine().getStatusCode(), responseSAML); //Parse SAML response BufferedReader brSAML = new BufferedReader(new InputStreamReader((responseSAML.getEntity().getContent()))); //responseSAML.close(); while ((outputSAML = brSAML.readLine()) != null) { if (outputSAML.contains("SAMLResponse")) { resultSAML = outputSAML.substring(outputSAML.indexOf("value=") + 7, outputSAML.indexOf("/>") - 1); break; } } httpClient.close(); return resultSAML; }
From source file:org.apache.manifoldcf.agents.output.amazoncloudsearch.AmazonCloudSearchConnector.java
private String postData(InputStream jsonData) throws ServiceInterruption, ManifoldCFException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w .j a v a 2s . c om BinaryInput bi = new TempFileInput(jsonData); try { poster.setEntity(new InputStreamEntity(bi.getStream(), bi.getLength())); HttpResponse res = httpclient.execute(poster); HttpEntity resEntity = res.getEntity(); return EntityUtils.toString(resEntity); } finally { bi.discard(); } } catch (ClientProtocolException e) { throw new ManifoldCFException(e); } catch (IOException e) { handleIOException(e); } finally { try { httpclient.close(); } catch (IOException e) { //do nothing } } return null; }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlStatusById(String crawlid) { String status = ""; System.out.println("get crawlid"); 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 {/* w w w . j av a2s . com*/ //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl/" + crawlid); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL + crawlid); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); String result = ""; BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result += inputLine; } in.close(); // TO-DO should be removed in the future and handle it more gracefully result = result.replace("u'", "'"); result = result.replace("'", "\""); JSONObject crawljson = new JSONObject(result); System.out.println("myObject " + crawljson.toString()); status = crawljson.getString("status"); EntityUtils.consume(response.getEntity()); } catch (JSONException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } 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 status; }
From source file:br.gov.sc.fatma.resourcemanager.commands.SiteCheckIfUPCommand.java
@Override public Status execute() { Logger.getLogger(SiteCheckIfUPCommand.class.getName()).log(Level.FINE, "-------- " + _site.getPath() + " Connection Testing ------"); Status result;/* w w w. j a v a2s. c om*/ CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet(_site); Logger.getLogger(SiteCheckIfUPCommand.class.getName()).log(Level.INFO, "Executing request " + httpget.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { return "200"; } else { return String.valueOf(status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); result = new Status(responseBody.equals("200"), "", Integer.valueOf(responseBody)); } catch (IOException ex) { Logger.getLogger(SiteCheckIfUPCommand.class.getName()).log(Level.WARNING, ex.getMessage(), ex); ex.printStackTrace(); result = new Status(false, ex.getMessage(), -1); } finally { try { httpclient.close(); } catch (IOException ex) { } } return result; }