List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:fr.logfiletoes.config.Unit.java
/** * Initialise ElasticSearch Index ans taile file * @throws IOException //from w w w .java 2 s . c o m */ public void start() throws IOException { httpclient = HttpClients.createDefault(); context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(getElasticSearch().getUrl()); if (getElasticSearch().getLogin() != null && getElasticSearch().getPassword() != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getElasticSearch().getLogin(), getElasticSearch().getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); context.setCredentialsProvider(credentialsProvider); } CloseableHttpResponse elasticSearchCheck = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check index : \"{0}\"", elasticSearchCheck.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheck.getEntity().getContent())); int statusCodeCheck = elasticSearchCheck.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheck.getEntity()); elasticSearchCheck.close(); if (statusCodeCheck == 404) { // Cration de l'index HttpPut httpPut = new HttpPut(getElasticSearch().getUrl()); CloseableHttpResponse executeCreateIndex = httpclient.execute(httpPut, context); LOG.log(Level.INFO, "Create index : \"{0}\"", executeCreateIndex.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(executeCreateIndex.getEntity().getContent())); EntityUtils.consume(executeCreateIndex.getEntity()); executeCreateIndex.close(); CloseableHttpResponse elasticSearchCheckCreate = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check create index : \"{0}\"", elasticSearchCheckCreate.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheckCreate.getEntity().getContent())); int statusCodeCheckCreate = elasticSearchCheckCreate.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheckCreate.getEntity()); elasticSearchCheckCreate.close(); if (statusCodeCheckCreate != 200) { LOG.log(Level.SEVERE, "unable to create index \"{0}\"", getElasticSearch().getUrl()); throw new IOException("unable to create index \"" + getElasticSearch().getUrl() + "\""); } } else if (elasticSearchCheck.getStatusLine().getStatusCode() != 200) { LOG.severe("unkown error elasticsearch"); throw new IOException("unkown error elasticsearch"); } LOG.log(Level.INFO, "Initialisation ElasticSearch r\u00e9ussi pour {0}", getElasticSearch().getUrl()); tailer = Tailer.create(getLogFile(), new TailerListenerUnit(this, httpclient, context)); }
From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java
@Test public void testGetPractitioners() throws Exception { String facadeUri = (String) facadeProps.get("facade.uri"); URIBuilder builder = new URIBuilder(facadeUri); URI uri = builder.setPath(builder.getPath() + "/Practitioner") .setParameter("_profile", "http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp").build(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("Accept", "application/json+fhir; charset=UTF-8"); CloseableHttpResponse response1 = httpclient.execute(httpGet); assertEquals(200, response1.getStatusLine().getStatusCode()); String json = null;//from ww w. ja va2 s. c om try { HttpEntity entity1 = response1.getEntity(); json = EntityUtils.toString(entity1); } finally { response1.close(); } assertNotNull(json); BundleParser conv = new BundleParser(); AtomFeed response = conv.fromJsonOrXml(json); assertNotEquals(0, response.getEntryList().size()); }
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsAndInterOpsDUnitTest.java
public static void doGetsUsingRestApis(String restEndpoint) { //HttpHeaders headers = setAcceptAndContentTypeHeaders(); String currentOperation = null; JSONObject jObject;//from w ww . j a v a 2 s .c om JSONArray jArray; try { //1. Get on key="1" and validate result. { currentOperation = "GET on key 1"; HttpGet get = new HttpGet(restEndpoint + "/People/1"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } jObject = new JSONObject(str.toString()); assertEquals(jObject.get("id"), 101); assertEquals(jObject.get("firstName"), "Mithali"); assertEquals(jObject.get("middleName"), "Dorai"); assertEquals(jObject.get("lastName"), "Raj"); assertEquals(jObject.get("gender"), Gender.FEMALE.name()); } //2. Get on key="16" and validate result. { currentOperation = "GET on key 16"; HttpGet get = new HttpGet(restEndpoint + "/People/16"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } jObject = new JSONObject(str.toString()); assertEquals(jObject.get("id"), 104); assertEquals(jObject.get("firstName"), "Shila"); assertEquals(jObject.get("middleName"), "kumari"); assertEquals(jObject.get("lastName"), "Dixit"); assertEquals(jObject.get("gender"), Gender.FEMALE.name()); } //3. Get all (getAll) entries in Region { HttpGet get = new HttpGet(restEndpoint + "/People"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse result = httpclient.execute(get); assertEquals(result.getStatusLine().getStatusCode(), 200); assertNotNull(result.getEntity()); HttpEntity entity = result.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line); } result.close(); try { jObject = new JSONObject(sb.toString()); jArray = jObject.getJSONArray("People"); assertEquals(jArray.length(), 16); } catch (JSONException e) { fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException "); } } //4. GetAll?limit=10 (10 entries) and verify results { HttpGet get = new HttpGet(restEndpoint + "/People?limit=10"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get); assertEquals(response.getStatusLine().getStatusCode(), 200); assertNotNull(response.getEntity()); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } try { jObject = new JSONObject(str.toString()); jArray = jObject.getJSONArray("People"); assertEquals(jArray.length(), 10); } catch (JSONException e) { fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException "); } } //5. Get keys - List all keys in region { HttpGet get = new HttpGet(restEndpoint + "/People/keys"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get); assertEquals(response.getStatusLine().getStatusCode(), 200); assertNotNull(response.getEntity()); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } try { jObject = new JSONObject(str.toString()); jArray = jObject.getJSONArray("keys"); assertEquals(jArray.length(), 16); } catch (JSONException e) { fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException "); } } //6. Get data for specific keys { HttpGet get = new HttpGet(restEndpoint + "/People/1,3,5,7,9,11"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get); assertEquals(response.getStatusLine().getStatusCode(), 200); assertNotNull(response.getEntity()); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } try { jObject = new JSONObject(str.toString()); jArray = jObject.getJSONArray("People"); assertEquals(jArray.length(), 6); } catch (JSONException e) { fail(" Rest Request ::" + currentOperation + " :: should not have thrown JSONException "); } } } catch (Exception e) { throw new RuntimeException("unexpected exception", e); } }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
private String fetchMetadataJson(String nodeUuid) { String fullUrl = String.format("%s/%s", metadataUrl, nodeUuid); logger.debug("url: {}", fullUrl); try {/*from www . j a v a 2s . c o m*/ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = createGetRequest(fullUrl); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); String result = CharStreams.toString(new InputStreamReader(entity.getContent(), "UTF-8")); response.close(); httpClient.close(); return result; } catch (IOException e) { throw new AlfrescoDownException(e); } }
From source file:com.navercorp.pinpoint.plugin.httpclient4.CloaeableHttpClientIT.java
@Test public void test() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w. j a v a 2s . co m*/ HttpGet httpget = new HttpGet("http://www.naver.com"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { instream.read(); } catch (IOException ex) { throw ex; } finally { instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", CloseableHttpClient.class.getMethod("execute", HttpUriRequest.class))); verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", PoolingHttpClientConnectionManager.class.getMethod("connect", HttpClientConnection.class, HttpRoute.class, int.class, HttpContext.class), annotation("http.internal.display", "www.naver.com:80"))); verifier.verifyTrace(event("HTTP_CLIENT_4", HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class, HttpContext.class), null, null, "www.naver.com", annotation("http.url", "/"), annotation("http.status.code", 200), annotation("http.io", anyAnnotationValue()))); verifier.verifyTraceCount(0); }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
private AlfrescoResponse getDocumentsActions(String url) { CloseableHttpClient httpClient = HttpClients.createDefault(); logger.debug("Hitting url: {}", url); try {/*from w w w .j a va 2 s.c o m*/ HttpGet httpGet = createGetRequest(url); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); AlfrescoResponse afResponse = fromHttpEntity(entity); EntityUtils.consume(entity); response.close(); httpClient.close(); return afResponse; } catch (IOException e) { logger.warn("Failed to fetch nodes.", e); throw new AlfrescoDownException("Alfresco appears to be down", e); } }
From source file:com.xx_dev.apn.proxy.test.TestProxyWithHttpClient.java
private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) { ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(2000);//w ww. java2s .com cm.setDefaultMaxPerRoute(40); cm.setDefaultConnectionConfig(connectionConfig); CloseableHttpClient httpClient = HttpClients.custom() .setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm) .disableContentCompression().disableCookieManagement().build(); HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort()); RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true) .setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000) .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); HttpGet request = new HttpGet(uri); request.setConfig(config); try { CloseableHttpResponse httpResponse = httpClient.execute(request); Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode()); if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) { Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue()); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseHandler.handleResponse(httpResponse); httpResponse.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:com.msds.km.service.Impl.DrivingLicenseRecognitionServcieiImpl.java
private String recognitionInternal(byte[] b) throws Exception { try {/*from w ww .j ava 2 s . c om*/ HttpPost httppost = new HttpPost(POST_URL); HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("img", b, ContentType.MULTIPART_FORM_DATA, "test.jpg") .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build(); httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { String content = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); return content; } catch (IOException e) { throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e); } finally { try { response.close(); } catch (IOException e) { throw new Exception( "can not post request to the url:" + POST_URL + ", please check the network.", e); } } } catch (ClientProtocolException e) { throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e); } catch (IOException e) { throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e); } }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.LocationsTest.java
@Test public void itGetsAListOfLocations() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:3333/crs/locations"); CloseableHttpResponse response = null; try {//from ww w. j av a2 s. com response = closeableHttpClient.execute(httpGet); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(jsonNode.get("locations").get(0).asText(), not(equalTo(""))); } finally { if (response != null) response.close(); } }
From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java
@Override public String executeUploadByteStream(String path, File file) throws IOException { if (this.conn.getConfig() == null) { throw new IllegalStateException("Can't execute HTTP request when configuration is undefined."); }/*from w ww . j av a2 s .c o m*/ String fullPath = this.conn.getConfig().getTcApiUrl() + path.replace("/api/", "/"); logger.trace("Calling POST: " + fullPath); HttpPost httpBase = new HttpPost(fullPath); httpBase.setEntity(new FileEntity(file)); String headerPath = httpBase.getURI().getRawPath() + "?" + httpBase.getURI().getRawQuery(); ConnectionUtil.applyHeaders(this.conn.getConfig(), httpBase, httpBase.getMethod(), headerPath, ContentType.APPLICATION_OCTET_STREAM.toString()); logger.trace("Request: " + httpBase.getRequestLine()); CloseableHttpResponse response = this.conn.getApiClient().execute(httpBase); String result = null; logger.trace(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { try { result = EntityUtils.toString(entity, "iso-8859-1"); logger.trace("Result:" + result); EntityUtils.consume(entity); } finally { response.close(); } } return result; }