Java Code Examples for org.apache.http.util.EntityUtils.consumeQuietly()

The following are Jave code examples for showing how to use consumeQuietly() of the org.apache.http.util.EntityUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: yacy_grid_mcp   File: ClientConnection.java   View Source Code Vote up 10 votes
/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header: httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring+ ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("no redirect for  " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}
 
Example 2
Project: datarouter   File: DatarouterHttpResponse.java   View Source Code Vote up 9 votes
public DatarouterHttpResponse(HttpResponse response, HttpClientContext context,
		Consumer<HttpEntity> httpEntityConsumer){
	this.response = response;
	this.cookies = context.getCookieStore().getCookies();
	if(response != null){
		this.statusCode = response.getStatusLine().getStatusCode();
		this.entity = "";

		HttpEntity httpEntity = response.getEntity();
		if(httpEntity == null){
			return;
		}
		if(httpEntityConsumer != null){
			httpEntityConsumer.accept(httpEntity);
			return;
		}
		try{
			this.entity = EntityUtils.toString(httpEntity);
		}catch(IOException e){
			logger.error("Exception occurred while reading HTTP response entity", e);
		}finally{
			EntityUtils.consumeQuietly(httpEntity);
		}
	}
}
 
Example 3
Project: elasticsearch_my   File: ClientYamlTestResponse.java   View Source Code Vote up 7 votes
ClientYamlTestResponse(Response response) throws IOException {
    this.response = response;
    if (response.getEntity() != null) {
        String contentType = response.getHeader("Content-Type");
        this.bodyContentType = XContentType.fromMediaTypeOrFormat(contentType);
        try {
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            //skip parsing if we got text back (e.g. if we called _cat apis)
            if (bodyContentType != null) {
                this.parsedResponse = ObjectPath.createFromXContent(bodyContentType.xContent(), new BytesArray(bytes));
            }
            this.body = bytes;
        } catch (IOException e) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw e;
        }
    } else {
        this.body = null;
        this.bodyContentType = null;
    }
}
 
Example 4
Project: r2cloud   File: RestClient.java   View Source Code Vote up 7 votes
public boolean healthy() {
	HttpGet m = new HttpGet(baseUrl + "/api/v1/health");
	HttpResponse response = null;
	try {
		response = httpclient.execute(m);
		int statusCode = response.getStatusLine().getStatusCode();
		boolean result = statusCode == HttpStatus.SC_OK;
		if (!result) {
			LOG.info("status code: " + statusCode);
		}
		return result;
	} catch (Exception e) {
		LOG.error("unable to get", e);
		return false;
	} finally {
		if (response != null) {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	}
}
 
Example 5
Project: r2cloud   File: RestClient.java   View Source Code Vote up 7 votes
public void setup(String keyword, String username, String password) {
	LOG.info("setup: " + username);
	HttpPost m = new HttpPost(baseUrl + "/api/v1/setup/setup");
	JsonObject json = Json.object();
	json.add("keyword", keyword);
	json.add("username", username);
	json.add("password", password);
	m.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
	HttpResponse response = null;
	try {
		response = httpclient.execute(m);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			LOG.info("response: " + EntityUtils.toString(response.getEntity()));
			throw new RuntimeException("invalid status code: " + statusCode);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	} finally {
		if (response != null) {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	}
}
 
Example 6
Project: r2cloud   File: RestClient.java   View Source Code Vote up 7 votes
public JsonObject getTle() {
	LOG.info("get tle");
	HttpGet m = new HttpGet(baseUrl + "/api/v1/admin/tle");
	m.addHeader("Authorization", "Bearer " + accessToken);
	HttpResponse response = null;
	try {
		response = httpclient.execute(m);
		int statusCode = response.getStatusLine().getStatusCode();
		String responseBody = EntityUtils.toString(response.getEntity());
		if (statusCode != HttpStatus.SC_OK) {
			LOG.info("response: " + responseBody);
			throw new RuntimeException("invalid status code: " + statusCode);
		}
		return (JsonObject) Json.parse(responseBody);
	} catch (Exception e) {
		throw new RuntimeException(e);
	} finally {
		if (response != null) {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	}
}
 
Example 7
Project: bubble2   File: ResponseWrap.java   View Source Code Vote up 7 votes
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context,
		ObjectMapper _mapper) {
	this.response = response;
	this.httpClient = httpClient;
	this.request = request;
	this.context = context;
	mapper = _mapper;

	try {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			this.entity = new BufferedHttpEntity(entity);
		} else {
			this.entity = new BasicHttpEntity();
		}

		EntityUtils.consumeQuietly(entity);
		this.response.close();
	} catch (IOException e) {
		logger.warn(e.getMessage());
	}
}
 
Example 8
Project: yacy_grid_mcp   File: ClientConnection.java   View Source Code Vote up 6 votes
public void close() {
    HttpEntity httpEntity = this.httpResponse.getEntity();
    if (httpEntity != null) EntityUtils.consumeQuietly(httpEntity);
    try {
        this.inputStream.close();
    } catch (IOException e) {} finally {
        this.request.releaseConnection();
    }
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@Override
public boolean isValidEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
        final int responseCode = response.getStatusLine().getStatusCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                LOGGER.debug("Response code from server matched {}.", responseCode);
                return true;
            }
        }

        LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}",
                responseCode);

        if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            final String value = response.getStatusLine().getReasonPhrase();
            LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(),
                    value);
        }

        entity = response.getEntity();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return false;
}
 
Example 10
Project: springboot-shiro-cas-mybatis   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@Override
public boolean isValidEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (final CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
        final int responseCode = response.getStatusLine().getStatusCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                LOGGER.debug("Response code from server matched {}.", responseCode);
                return true;
            }
        }

        LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}",
                responseCode);

        if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            final String value = response.getStatusLine().getReasonPhrase();
            LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(),
                    value);
        }

        entity = response.getEntity();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return false;
}
 
Example 11
Project: cas-5.1.0   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@Override
public HttpMessage sendMessageToEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
        final int responseCode = response.getStatusLine().getStatusCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                LOGGER.debug("Response code received from server matched [{}].", responseCode);
                entity = response.getEntity();
                final HttpMessage msg = new HttpMessage(url, IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8));
                msg.setContentType(entity.getContentType().getValue());
                msg.setResponseCode(responseCode);
                return msg;
            }
        }
        LOGGER.warn("Response code [{}] from [{}] did not match any of the acceptable response codes.",
                responseCode, url);
        if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            final String value = response.getStatusLine().getReasonPhrase();
            LOGGER.error("There was an error contacting the endpoint: [{}]; The error:\n[{}]", url.toExternalForm(),
                    value);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return null;
}
 
Example 12
Project: cas-5.1.0   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@Override
public boolean isValidEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
        final int responseCode = response.getStatusLine().getStatusCode();

        final int idx = Collections.binarySearch(this.acceptableCodes, responseCode);
        if (idx >= 0) {
            LOGGER.debug("Response code from server matched [{}].", responseCode);
            return true;
        }

        LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was [{}]", responseCode);

        if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            final String value = response.getStatusLine().getReasonPhrase();
            LOGGER.error("There was an error contacting the endpoint: [{}]; The error was:\n[{}]", url.toExternalForm(), value);
        }

        entity = response.getEntity();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return false;
}
 
Example 13
Project: cas-server-4.2.1   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@Override
public boolean isValidEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (final CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
        final int responseCode = response.getStatusLine().getStatusCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                LOGGER.debug("Response code from server matched {}.", responseCode);
                return true;
            }
        }

        LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}",
                responseCode);

        if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            final String value = response.getStatusLine().getReasonPhrase();
            LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(),
                    value);
        }

        entity = response.getEntity();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    return false;
}
 
Example 14
Project: hadoop   File: AuthenticatorTestCase.java   View Source Code Vote up 6 votes
private void doHttpClientRequest(HttpClient httpClient, HttpUriRequest request) throws Exception {
  HttpResponse response = null;
  try {
    response = httpClient.execute(request);
    final int httpStatus = response.getStatusLine().getStatusCode();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, httpStatus);
  } finally {
    if (response != null) EntityUtils.consumeQuietly(response.getEntity());
  }
}
 
Example 15
Project: JavaNRPC   File: EtcdClient.java   View Source Code Vote up 6 votes
private static void close(HttpResponse response) {
    if (response == null) {
        return;
    }

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        EntityUtils.consumeQuietly(entity);
    }
}
 
Example 16
Project: vartrans   File: HttpClientPool.java   View Source Code Vote up 4 votes
private String getResponseContent(String url, HttpRequestBase request) throws Exception {
    HttpResponse response = null;
    try {
        response = this.getHttpClient(2000,2000).execute(request);
        return EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        throw new Exception("got an error from HTTP for url : " + URLDecoder.decode(url, "UTF-8"),e);
    } finally {
        if(response != null){
            EntityUtils.consumeQuietly(response.getEntity());
        }
        request.releaseConnection();
    }
}