List of usage examples for org.apache.http.util EntityUtils consume
public static void consume(HttpEntity httpEntity) throws IOException
From source file:org.commonjava.maven.galley.transport.htcli.internal.util.TransferResponseUtils.java
public static boolean handleUnsuccessfulResponse(final HttpUriRequest request, final CloseableHttpResponse response, HttpLocation location, final String url, final boolean graceful404) throws TransferException { final Logger logger = LoggerFactory.getLogger(TransferResponseUtils.class); final StatusLine line = response.getStatusLine(); InputStream in = null;// w ww .j a va 2 s .co m HttpEntity entity = null; try { entity = response.getEntity(); final int sc = line.getStatusCode(); boolean contentMissing = (sc == HttpStatus.SC_NOT_FOUND || sc == HttpStatus.SC_GONE); if (graceful404 && contentMissing) { return false; } else { ByteArrayOutputStream out = null; if (entity != null) { in = entity.getContent(); out = new ByteArrayOutputStream(); copy(in, out); } if (NON_SERVER_GATEWAY_ERRORS.contains(sc) || (sc > 499 && sc < 599)) { throw new BadGatewayException(location, url, sc, "HTTP request failed: %s%s", line, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } else if (contentMissing) { throw new TransferException("HTTP request failed: %s\nURL: %s%s", line, url, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } else { throw new TransferLocationException(location, "HTTP request failed: %s%s", line, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } } } catch (final IOException e) { request.abort(); throw new TransferLocationException(location, "Error reading body of unsuccessful request.\nStatus: %s.\nURL: %s.\nReason: %s", e, line, url, e.getMessage()); } finally { IOUtils.closeQuietly(in); if (entity != null) { try { EntityUtils.consume(entity); } catch (final IOException e) { logger.debug("Failed to consume entity: " + e.getMessage(), e); } } } }
From source file:com.bigdata.rdf.sail.webapp.client.BackgroundGraphResult.java
@Override public void run() { boolean completed = false; parserThread = Thread.currentThread(); try {// w ww .j a v a 2 s . co m parser.setRDFHandler(this); if (charset == null) { parser.parse(in, baseURI); } else { parser.parse(new InputStreamReader(in, charset), baseURI); } EntityUtils.consume(entity); completed = true; } catch (RDFHandlerException e) { // parsing was cancelled or interrupted } catch (RDFParseException e) { queue.toss(e); } catch (IOException e) { queue.toss(e); } finally { parserThread = null; queue.done(); if (!completed) { try { EntityUtils.consume(entity); } catch (IOException ex) { } } } }
From source file:com.zazuko.blv.outbreak.tools.SparqlClient.java
List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(endpoint); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("query", query)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try {//from w w w . jav a 2 s. com HttpEntity entity2 = response2.getEntity(); InputStream in = entity2.getContent(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler(); xmlReader.setContentHandler(sparqlsResultsHandler); xmlReader.parse(new InputSource(in)); /* for (int ch = in.read(); ch != -1; ch = in.read()) { System.out.print((char)ch); } */ // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); return sparqlsResultsHandler.getResults(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException ex) { throw new RuntimeException(ex); } finally { response2.close(); } }
From source file:httputils.RavelloHttpClient.java
public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay, String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized) throws RavelloException, InterruptedException { JsonObject value = null;/* w w w .j ava 2 s . co m*/ HttpResponse response = null; try { response = this.getBlueprint(blueprintId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: " + response.getStatusLine().toString()); } JsonObject vmTemp = HttpUtil.convertResponseToJson(response); EntityUtils.consume(response.getEntity()); JsonBuilderFactory factory = Json.createBuilderFactory(null); Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator(); JsonObjectBuilder builder = factory.createObjectBuilder(); Map.Entry<String, JsonValue> ent; while (it.hasNext()) { ent = it.next(); if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) { builder.add(ent.getKey(), ent.getValue()); } } builder.add("name", applicationName); value = builder.build(); vmTemp = null; response = this.createApplication(value); this.verifyResponseAndConsume(response, "Failed to create application - error: "); value = HttpUtil.convertResponseToJson(response); EntityUtils.consumeQuietly(response.getEntity()); int appId = value.getInt("id"); if (costOptimized) { value = factory.createObjectBuilder().add("startAllVms", startAllVms).build(); } else { value = factory.createObjectBuilder().add("startAllVms", startAllVms) .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion) .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build(); } response = this.post("/applications/" + appId + "/publish", value); this.verifyResponseAndConsume(response, "Failed to publish application - error: "); value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build(); response = this.post("/applications/" + appId + "/setExpiration", value); if (!HttpUtil.verifyResponseAndConsume(response)) { throw new RavelloException("Failed to set expiration time for application - error: " + response.getStatusLine().toString() + "\n" + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED"); } if (!startAllVms) { response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); return value; } String state; JsonArray jArr; boolean allStarted; while (true) { allStarted = true; response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); jArr = value.getJsonObject("deployment").getJsonArray("vms"); for (int jt = 0; jt < jArr.size(); jt++) { state = jArr.getJsonObject(jt).getString("state"); allStarted = state.equals("STARTED"); if (state.equals("ERROR")) { throw new RavelloException( "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start"); } if (!allStarted) { break; } } if (allStarted) { break; } else { EntityUtils.consumeQuietly(response.getEntity()); Thread.sleep(20000); } } } catch (ClientProtocolException e) { throw new RavelloException("ClientProtocolException - " + e.getMessage()); } catch (IOException e) { throw new RavelloException("IOException - " + e.getMessage()); } catch (NullPointerException e) { throw new RavelloException("NullPointerException - " + e.getMessage()); } Thread.sleep(startupDelay * 1000); return value; }
From source file:eu.delving.sip.files.LinkChecker.java
private LinkCheck linkCheckRequest(String url) throws IOException { HttpHead head = new HttpHead(url); HttpResponse response = httpClient.execute(head); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { HttpGet get = new HttpGet(url); response = httpClient.execute(get); status = response.getStatusLine(); }/* w ww . j a v a2 s . co m*/ LinkCheck linkCheck = new LinkCheck(); linkCheck.httpStatus = status.getStatusCode(); linkCheck.time = System.currentTimeMillis(); Header contentType = response.getLastHeader("Content-Type"); linkCheck.mimeType = contentType == null ? null : contentType.getValue(); Header contentLength = response.getLastHeader("Content-Length"); linkCheck.fileSize = contentLength == null ? -1 : Integer.parseInt(contentLength.getValue()); linkCheck.ok = linkCheck.httpStatus == HttpStatus.SC_OK; EntityUtils.consume(response.getEntity()); return linkCheck; }
From source file:com.jaeksoft.searchlib.remote.UriHttp.java
public void close() { try {//from w ww. j a v a2s. co m if (httpEntity != null) { EntityUtils.consume(httpEntity); httpEntity = null; } } catch (IOException e) { Logging.warn(e.getMessage(), e); httpEntity = null; } if (httpResponse != null) { IOUtils.closeQuietly(httpResponse); httpResponse = null; } if (httpClient != null) { IOUtils.closeQuietly(httpClient); httpClient = null; } }
From source file:io.github.hebra.elasticsearch.beat.meterbeat.device.dlink.DSPW215.java
@Override public String fetchData() { final String url = config.getBaseurl().concat("/my_cgi.cgi?") .concat(new BigInteger(130, secureRandom).toString(32)); try {/*from w ww . jav a 2 s . co m*/ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build(); HttpClient client = HttpClientBuilder.create().setConnectionTimeToLive(5, TimeUnit.SECONDS) .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).build(); HttpPost post = new HttpPost(url); post.setConfig(requestConfig); post.setHeader("User-Agent", USER_AGENT); post.setHeader("Accept-Language", "en-US,en;q=0.5"); final List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("request", "create_chklst")); post.setEntity(new UrlEncodedFormEntity(urlParameters)); final HttpResponse response = client.execute(post); final String content = IOUtils.toString(response.getEntity().getContent(), Charsets.US_ASCII); EntityUtils.consume(response.getEntity()); return content.split("Meter Watt: ", 2)[1].trim(); } catch (IOException ioEx) { log.error("Timeout when trying to read from {} on {}: {}", config.getName(), config.getBaseurl(), ioEx.getMessage()); } return null; }
From source file:com.mycompany.bankinterface.eth.EthereumEidProvider.java
private String postJsonMessage(JSONObject jo) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(dest); httpPost.setHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8")); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); String content = IOUtils.toString(entity.getContent()); EntityUtils.consume(entity); return content; }/*from w w w . j a v a 2 s . co m*/ }
From source file:zz.pseas.ghost.client.GhostClient.java
public String execute(HttpUriRequest request, String charset) { DownloadUtil.setUserAgent(request);/*from w w w. j a v a 2 s. co m*/ String ans = null; try { CloseableHttpResponse resp = client.execute(request, context); ans = EntityUtils.toString(resp.getEntity(), charset); EntityUtils.consume(resp.getEntity()); } catch (IOException e) { ans = null; } finally { if (request instanceof HttpGet) { ((HttpGet) request).releaseConnection(); } else if (request instanceof HttpPost) { ((HttpPost) request).releaseConnection(); } else { } } return ans; }
From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java
@Test public void testListAll() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); LOG.info("Connecting to " + uri.toString()); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); assertEquals(doc.getHiredJudges().size(), 4); EntityUtils.consume(entity); }// ww w .ja v a 2s. com }