List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:io.confluent.rest.SaslTest.java
@Test public void testAuthorizedAttempt() throws Exception { CloseableHttpResponse response = null; try {//ww w . j ava2 s .c o m response = makeGetRequest(httpUri + "/principal", "bmVoYTpha2Zhaw=="); // neha's user/pass assertEquals(Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); assertEquals("neha", EntityUtils.toString(response.getEntity())); response.close(); response = makeGetRequest(httpUri + "/role/Administrators", "bmVoYTpha2Zhaw=="); // neha's user/pass assertEquals(Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); assertEquals("true", EntityUtils.toString(response.getEntity())); response.close(); response = makeGetRequest(httpUri + "/role/blah", "bmVoYTpha2Zhaw=="); // neha's user/pass assertEquals(Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); assertEquals("false", EntityUtils.toString(response.getEntity())); response.close(); assertMetricsCollected(); } finally { if (response != null) { response.close(); } } }
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);/*from w w w .j a v a2 s.c om*/ 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:cn.org.once.cstack.cli.rest.RestUtils.java
/** * sendPutCommand/*from ww w .j a va 2 s . com*/ * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPutCommand(String url, Map<String, Object> credentials, Map<String, String> parameters) throws ManagerResponseException { Map<String, Object> response = new HashMap<String, Object>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-type", "application/json"); try { ObjectMapper mapper = new ObjectMapper(); StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters)); httpPut.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPut, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
From source file:org.apache.geode.rest.internal.web.controllers.RestAPITestBase.java
void assertHttpResponse(CloseableHttpResponse response, int httpCode, int expectedServerResponses) { assertEquals(httpCode, response.getStatusLine().getStatusCode()); // verify response has body flag, expected is true. assertNotNull(response.getEntity()); try {/*from w w w .j a v a 2s . co m*/ String httpResponseString = processHttpResponse(response); response.close(); System.out.println("Response : " + httpResponseString); // verify function execution result JSONArray resultArray = new JSONArray(httpResponseString); assertEquals(expectedServerResponses, resultArray.length()); } catch (Exception e) { // fail("exception", e); } }
From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java
@Override public String GetStringContent(String url, List<Pair<String, String>> queryParams) { try {/*w w w.j ava2 s .co m*/ HttpGet httpget = new HttpGet(url); // The Hadoop Web HDFS only serves json, but no harm in being explicit. httpget.setHeader("accept", "application/json"); URIBuilder builder = new URIBuilder(url); for (Pair<String, String> queryParam : queryParams) { builder.addParameter(queryParam.getFirst(), queryParam.getSecond()); } httpget.setURI(builder.build()); CloseableHttpResponse response = clientImpl.execute(httpget); try { HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity); } finally { // I believe this releases the connection to the client pool, but does not // close the connection. response.close(); } } catch (IOException | URISyntaxException ex) { throw new RuntimeException("Apache method get string content: " + ex.getMessage()); } }
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 {//w ww .j a va2s . c om 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:com.code42.demo.RestInvoker.java
/** * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid * If the file is succesfully uploaded the response code of 204 is returned. * /* w ww .j a v a2 s .c o m*/ * @param planUid * @param sessionId * @param file * @return HTTP Response code as int * @throws Exception */ public int postFileAPI(String planUid, String sessionId, File file) throws Exception { int respCode; HttpClientBuilder hcs; CloseableHttpClient httpClient; hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (ssl) { hcs.setSSLSocketFactory(sslsf); } httpClient = hcs.build(); StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN); StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN); try { HttpPost httpPost = new HttpPost(ePoint + "/api/File"); FileBody fb = new FileBody(file); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId) .addPart("sessionId", sId).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse resp = httpClient.execute(httpPost); try { m_log.info("executing " + httpPost.getRequestLine()); m_log.info(resp.getStatusLine()); respCode = resp.getStatusLine().getStatusCode(); } finally { resp.close(); } } finally { httpClient.close(); } return respCode; }
From source file:coyote.dx.web.TestHtmlWorker.java
/** * This is a control test to make sure the HTTP server is running and the * test file is accessible/* w ww . ja va 2s . com*/ */ @Test public void baseServerTest() throws ClientProtocolException, IOException { CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet("http://localhost:" + port + "/data/test.html"); httpGet.addHeader("if-none-match", "*"); CloseableHttpClient httpClient = HttpClients.createDefault(); response = httpClient.execute(httpGet); assertEquals(200, response.getStatusLine().getStatusCode()); } finally { if (response != null) { response.close(); } } }
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPITestBase.java
protected void assertHttpResponse(CloseableHttpResponse response, int httpCode, int expectedServerResponses) { assertEquals(httpCode, response.getStatusLine().getStatusCode()); //verify response has body flag, expected is true. assertNotNull(response.getEntity()); try {/*www. ja va 2 s . c om*/ String httpResponseString = processHttpResponse(response); response.close(); LogWriterUtils.getLogWriter().info("Response : " + httpResponseString); //verify function execution result JSONArray resultArray = new JSONArray(httpResponseString); assertEquals(resultArray.length(), expectedServerResponses); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.cjan.test_collector.Uploader.java
/** * Upload test run and tests to CJAN.org. * * @param groupId groupId/*w ww .ja v a2 s . c om*/ * @param artifactId artifactId * @param version version * @param envProps environment properties * @param testResults test results * @throws UploadException if it fails to upload */ public String upload(String groupId, String artifactId, String version, EnvironmentProperties envProps, TestResults testResults) throws UploadException { validate(groupId, "Missing groupId"); validate(artifactId, "Missing artifactId"); validate(version, "Missing version"); validate(envProps, "Missing environment properties"); validate(testResults, "Empty test suite"); LOGGER.info("Uploading test results to CJAN.org"); final TestRun testRun = new TestRun(groupId, artifactId, version, envProps, testResults.getGeneralStatus()); testRun.addTests(testResults.getTests()); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Test Run: " + testRun.toString()); } final ObjectMapper mapper = new ObjectMapper(); final String json; try { json = mapper.writeValueAsString(testRun); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Test Run: " + testRun.toString()); } } catch (JsonGenerationException e) { throw new UploadException("Error converting test run to JSON: " + e.getMessage(), e); } catch (JsonMappingException e) { throw new UploadException("Error mapping object fields: " + e.getMessage(), e); } catch (IOException e) { throw new UploadException("IO error: " + e.getMessage(), e); } final CloseableHttpClient httpclient = HttpClients.createDefault(); try { RequestConfig config = null; if (isProxyEnabled()) { LOGGER.fine("Using HTTP proxy!"); final HttpHost proxy = new HttpHost(getProxyHost(), Integer.parseInt(getProxyPort())); config = RequestConfig.custom().setProxy(proxy).build(); } final HttpPost post = new HttpPost(getUrl()); if (config != null) { post.setConfig(config); } // add access token to headers post.addHeader("x-access-token", getAccessToken()); // post testrun, get ID back from server, show to user List<NameValuePair> pairs = new ArrayList<NameValuePair>(1); pairs.add(new BasicNameValuePair("json", json)); post.setEntity(new UrlEncodedFormEntity(pairs)); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); return body; } finally { response.close(); } } catch (ClientProtocolException e) { throw new UploadException("Client protocol error: " + e.getMessage(), e); } catch (IOException e) { throw new UploadException("IO error: " + e.getMessage(), e); } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Error closing HTTP client: " + e.getMessage(), e); } } } }