List of usage examples for org.apache.http.util EntityUtils consume
public static void consume(HttpEntity httpEntity) throws IOException
From source file:com.apm4all.tracy.TracyCloseableHttpClientPublisher.java
private String extractPostResponse(CloseableHttpResponse response) throws ParseException, IOException { StringBuilder sb = new StringBuilder(1024); HttpEntity entity = response.getEntity(); sb.append(response.getStatusLine()); sb.append(" "); sb.append(EntityUtils.toString(entity, StandardCharsets.UTF_8)); EntityUtils.consume(entity); return sb.toString(); }
From source file:com.econcept.pingconnectionutility.utility.PingConnectionUtility.java
private static void httpPingable(String targetURI) throws IOException, URISyntaxException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(targetURI)); CloseableHttpResponse response = httpClient.execute(httpGet); int currentCode = response.getStatusLine().getStatusCode(); try {//from w ww .jav a 2 s . c o m if (currentCode >= 200 && currentCode < 300) { HttpEntity entity = response.getEntity(); InputStream responseStream = entity.getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(responseStream, writer, "UTF-8"); System.out.println("Target Server are ok: " + currentCode); System.out.println(writer.toString()); EntityUtils.consume(entity); } // if else { System.out.println("Target Server are not ok: " + currentCode); } // else } // try finally { response.close(); } // finally }
From source file:com.github.restdriver.clientdriver.integration.BodyCaptureTest.java
@Test public void canCaptureRequestBodyAsString() throws Exception { StringBodyCapture capture = new StringBodyCapture(); clientDriver.addExpectation(onRequestTo("/foo").withMethod(Method.POST).capturingBodyIn(capture), giveEmptyResponse().withStatus(201)); HttpClient client = new DefaultHttpClient(); HttpPost correctPost = new HttpPost(clientDriver.getBaseUrl() + "/foo"); correctPost.setEntity(new StringEntity("a string")); HttpResponse correctResponse = client.execute(correctPost); EntityUtils.consume(correctResponse.getEntity()); assertThat(capture.getContent(), is("a string")); }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the POST way.</p> * //from w w w . java 2 s . c o m * @param url request URI * @param json request parameter(json format string) * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String post(String url, String json, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; String result = null; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setEntity(new StringEntity(json, "UTF-8")); httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("POST?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:br.com.atmatech.sac.webService.WebServiceFinanceiro.java
public List<FinanceiroBeans> getFinanceiro(String url, String user, String password) throws IOException { String chave = ""; HttpPost post = new HttpPost(url); boolean result = false; /* Configura os parmetros do POST */ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("login", user)); nameValuePairs.add(new BasicNameValuePair("senha", password)); nameValuePairs.add(new BasicNameValuePair("x", "26")); nameValuePairs.add(new BasicNameValuePair("y", "26")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8)); // post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0"); HttpResponse response = client.execute(post); // System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(response.getEntity()); HttpPost get = new HttpPost("http://atma.serveftp.com/atma/view/index.php?page=BAIXAR&mostrar=1"); get.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8)); response = client.execute(get);//from www . j ava 2s. co m BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; // // Grava pagina no arquivo FileWriter out = new FileWriter("./logfin.txt"); PrintWriter gravarArq = new PrintWriter(out); int indexant = 11; boolean doc = true; boolean cliente = true; boolean valor = true; boolean vencimento = true; boolean contato = true; boolean tel = true; String tdoc = ""; String tcliente = ""; float tvalor = 0; Date tvencimento = null; String tcontato = ""; String ttel = ""; List<FinanceiroBeans> lfb = new ArrayList<>(); while ((line = rd.readLine()) != null) { if (line.contains("<tr><td>")) { //gravarArq.print(line+"\n"); line = line.replace("<tr><td>", "\n").replace("</td></tr>", "\n"); line = line.replace("</td><td>", ";") .replace("</td><td align='center'><a class='btn default' target='_blank'", ";") .replace("</i></a>", ":"); gravarArq.print(line + "\n"); for (int i = 0; i < line.length(); i++) { if (doc && (indexant != i)) { if (line.charAt(i) == ';') { tdoc = line.substring(indexant + 1, i); indexant = i; doc = false; } } else { if ((!doc) && (cliente) && (indexant != i)) { if (line.charAt(i) == ';') { tcliente = line.substring(indexant + 1, i); indexant = i; cliente = false; } } else { if ((!doc) && (!cliente) && (valor) && (indexant != i)) { if (line.charAt(i) == ';') { tvalor = Float.valueOf(line.substring(indexant + 1, i)); indexant = i; valor = false; } } else { if ((!doc) && (!cliente) && (!valor) && (vencimento) && (indexant != i)) { if (line.charAt(i) == ';') { String data = line.substring(indexant + 1, i).replace("/", "."); int ind1 = data.indexOf("."); int ind2 = data.indexOf(".", ind1 + 1); String dd = data.substring(0, ind1); String mm = data.substring(ind1 + 1, ind2); String yyyy = data.substring(ind2 + 1); tvencimento = new Date(Integer.parseInt(yyyy) - 1900, Integer.parseInt(mm) - 1, Integer.parseInt(dd)); indexant = i; vencimento = false; } } else { if ((!doc) && (!cliente) && (!valor) && (!vencimento) && (contato) && (indexant != i)) { if (line.charAt(i) == ';') { tcontato = line.substring(indexant + 1, i); indexant = i; contato = false; } } else { if ((!doc) && (!cliente) && (!valor) && (!vencimento) && (!contato) && (tel) && (indexant != i)) { if (line.charAt(i) == ';') { ttel = line.substring(indexant + 1, i); indexant = i; tel = false; } } else { if ((!doc) && (!cliente) && (!valor) && (!vencimento) && (!contato) && (!tel) && (line.charAt(i) == ':')) { indexant = i + 2; FinanceiroBeans fb = new FinanceiroBeans(); fb.setCliente(tcliente); fb.setContato(tcontato); fb.setDoc(tdoc); fb.setTelcel(ttel); fb.setValor(tvalor); fb.setVencimento(tvencimento); lfb.add(fb); doc = true; cliente = true; valor = true; vencimento = true; contato = true; tel = true; } } } } } } } } } } out.close(); return lfb; }
From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpRollupsQueryHandlerIntegrationTest.java
@Test public void testHttpRollupsQueryHandler() throws Exception { String postfix = getPostfix(); // ingest and rollup metrics with enum values and verify CF points and elastic search indexes final String metric_name = "3333333.G1s" + postfix; // post multi metrics for ingestion and verify HttpResponse response = postMetric(tenant_id, postAggregatedPath, "sample_payload.json", postfix); assertEquals("Should get status 200 from ingestion server for POST", 200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); JsonObject responseObject = getSingleMetricRetry(tenant_id, metric_name, start, end, "", "FULL", ""); assertNotNull("No values for " + metric_name + " found", responseObject); assertEquals("unknown", responseObject.get("unit").getAsString()); JsonArray values = responseObject.getAsJsonArray("values"); assertEquals(1, values.size());/*from ww w .j av a 2 s . co m*/ JsonObject value = values.get(0).getAsJsonObject(); assertEquals(1, value.get("numPoints").getAsInt()); assertTrue(value.has("timestamp")); assertEquals(397, value.get("latest").getAsInt()); JsonObject meta = responseObject.get("metadata").getAsJsonObject(); assertTrue(meta.get("limit").isJsonNull()); assertTrue(meta.get("next_href").isJsonNull()); assertEquals(1, meta.get("count").getAsInt()); assertTrue(meta.get("marker").isJsonNull()); assertResponseHeaderAllowOrigin(response); }
From source file:guru.nidi.loader.url.SimpleUrlFetcher.java
@Override public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name, long ifModifiedSince) throws IOException { final String suffix = (name == null || name.length() == 0) ? "" : ("/" + encodeUrl(name)); final HttpGet get = postProcessGet(new HttpGet(base + suffix)); if (ifModifiedSince > 0) { get.addHeader("if-modified-since", httpDate(ifModifiedSince)); }//from www.j a va 2s . c om final CloseableHttpResponse getResult = client.execute(get); switch (getResult.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: // remove AutoCloseInputStream as soon as // https://github.com/raml-org/raml-java-parser/issues/72 is fixed return new AutoCloseInputStream(getResult.getEntity().getContent()); case HttpStatus.SC_NOT_MODIFIED: EntityUtils.consume(getResult.getEntity()); return null; default: throw new IOException("Http response status not ok: " + getResult.getStatusLine().toString()); } }
From source file:me.zhuoran.crawler4j.crawler.http.HttpFetchResult.java
/** * Ensures that the entity content is fully consumed and the content stream, if exists, is closed. * //from ww w . j a v a 2s . c o m */ public void consume() { try { if (entity != null) { EntityUtils.consume(entity); } } catch (EOFException e) { // We can ignore this exception. It can happen on compressed streams // which are not // repeatable } catch (IOException e) { // We can ignore this exception. It can happen if the stream is // closed. } catch (Exception e) { e.printStackTrace(); } }
From source file:de.intevation.irix.ImageClient.java
/** Obtains a Report from mapfish-print service. * * @param imageUrl The url to send the request to. * @param timeout the timeout for the httpconnection. * * @return byte[] with the report./*from www. j av a2 s . c o m*/ * * @throws IOException if communication with print service failed. * @throws ImageException if the print job failed. */ public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException { RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build(); HttpGet get = new HttpGet(imageUrl); CloseableHttpResponse resp = client.execute(get); StatusLine status = resp.getStatusLine(); byte[] retval = null; try { HttpEntity respEnt = resp.getEntity(); InputStream in = respEnt.getContent(); if (in != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[BYTE_ARRAY_SIZE]; int r; while ((r = in.read(buf)) >= 0) { out.write(buf, 0, r); } retval = out.toByteArray(); } finally { in.close(); EntityUtils.consume(respEnt); } } } finally { resp.close(); } if (status.getStatusCode() < HttpURLConnection.HTTP_OK || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) { if (retval != null) { throw new ImageException(new String(retval)); } else { throw new ImageException("Communication with print service '" + imageUrl + "' failed." + "\nNo response from print service."); } } return retval; }