use of org.apache.http.client.protocol.HttpClientContext in project crate by crate.
the class BlobHttpIntegrationTest method getRedirectLocations.
public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address) throws IOException {
CloseableHttpResponse response = null;
try {
HttpClientContext context = HttpClientContext.create();
HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri));
response = client.execute(httpHead, context);
List<URI> redirectLocations = context.getRedirectLocations();
if (redirectLocations == null) {
// client might not follow redirects automatically
if (response.containsHeader("location")) {
List<String> redirects = new ArrayList<>(1);
for (Header location : response.getHeaders("location")) {
redirects.add(location.getValue());
}
return redirects;
}
return Collections.emptyList();
}
List<String> redirects = new ArrayList<>(1);
for (URI redirectLocation : redirectLocations) {
redirects.add(redirectLocation.toString());
}
return redirects;
} finally {
if (response != null) {
IOUtils.closeWhileHandlingException(response);
}
}
}
use of org.apache.http.client.protocol.HttpClientContext in project elasticsearch by elastic.
the class RestClient method performRequestAsync.
private void performRequestAsync(final long startTime, final HostTuple<Iterator<HttpHost>> hostTuple, final HttpRequestBase request, final Set<Integer> ignoreErrorCodes, final HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory, final FailureTrackingResponseListener listener) {
final HttpHost host = hostTuple.hosts.next();
//we stream the request body if the entity allows for it
final HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(host, request);
final HttpAsyncResponseConsumer<HttpResponse> asyncResponseConsumer = httpAsyncResponseConsumerFactory.createHttpAsyncResponseConsumer();
final HttpClientContext context = HttpClientContext.create();
context.setAuthCache(hostTuple.authCache);
client.execute(requestProducer, asyncResponseConsumer, context, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse httpResponse) {
try {
RequestLogger.logResponse(logger, request, host, httpResponse);
int statusCode = httpResponse.getStatusLine().getStatusCode();
Response response = new Response(request.getRequestLine(), host, httpResponse);
if (isSuccessfulResponse(statusCode) || ignoreErrorCodes.contains(response.getStatusLine().getStatusCode())) {
onResponse(host);
listener.onSuccess(response);
} else {
ResponseException responseException = new ResponseException(response);
if (isRetryStatus(statusCode)) {
//mark host dead and retry against next one
onFailure(host);
retryIfPossible(responseException);
} else {
//mark host alive and don't retry, as the error should be a request problem
onResponse(host);
listener.onDefinitiveFailure(responseException);
}
}
} catch (Exception e) {
listener.onDefinitiveFailure(e);
}
}
@Override
public void failed(Exception failure) {
try {
RequestLogger.logFailedRequest(logger, request, host, failure);
onFailure(host);
retryIfPossible(failure);
} catch (Exception e) {
listener.onDefinitiveFailure(e);
}
}
private void retryIfPossible(Exception exception) {
if (hostTuple.hosts.hasNext()) {
//in case we are retrying, check whether maxRetryTimeout has been reached
long timeElapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
long timeout = maxRetryTimeoutMillis - timeElapsedMillis;
if (timeout <= 0) {
IOException retryTimeoutException = new IOException("request retries exceeded max retry timeout [" + maxRetryTimeoutMillis + "]");
listener.onDefinitiveFailure(retryTimeoutException);
} else {
listener.trackFailure(exception);
request.reset();
performRequestAsync(startTime, hostTuple, request, ignoreErrorCodes, httpAsyncResponseConsumerFactory, listener);
}
} else {
listener.onDefinitiveFailure(exception);
}
}
@Override
public void cancelled() {
listener.onDefinitiveFailure(new ExecutionException("request was cancelled", null));
}
});
}
use of org.apache.http.client.protocol.HttpClientContext in project camel by apache.
the class HttpPollingConsumer method doReceive.
protected Exchange doReceive(int timeout) {
Exchange exchange = endpoint.createExchange();
HttpRequestBase method = createMethod(exchange);
HttpClientContext httpClientContext = new HttpClientContext();
// set optional timeout in millis
if (timeout > 0) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).build();
httpClientContext.setRequestConfig(requestConfig);
}
HttpEntity responeEntity = null;
try {
// execute request
HttpResponse response = httpClient.execute(method, httpClientContext);
int responseCode = response.getStatusLine().getStatusCode();
responeEntity = response.getEntity();
Object body = HttpHelper.readResponseBodyFromInputStream(responeEntity.getContent(), exchange);
// lets store the result in the output message.
Message message = exchange.getOut();
message.setBody(body);
// lets set the headers
Header[] headers = response.getAllHeaders();
HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
for (Header header : headers) {
String name = header.getName();
// mapping the content-type
if (name.toLowerCase().equals("content-type")) {
name = Exchange.CONTENT_TYPE;
}
String value = header.getValue();
if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
message.setHeader(name, value);
}
}
message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
if (response.getStatusLine() != null) {
message.setHeader(Exchange.HTTP_RESPONSE_TEXT, response.getStatusLine().getReasonPhrase());
}
return exchange;
} catch (IOException e) {
throw new RuntimeCamelException(e);
} finally {
if (responeEntity != null) {
try {
EntityUtils.consume(responeEntity);
} catch (IOException e) {
// nothing what we can do
}
}
}
}
use of org.apache.http.client.protocol.HttpClientContext in project spring-security-oauth by spring-projects.
the class ServerRunning method createRestTemplate.
public RestOperations createRestTemplate() {
RestTemplate client = new RestTemplate();
client.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
HttpClientContext context = HttpClientContext.create();
Builder builder = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setAuthenticationEnabled(false).setRedirectsEnabled(false);
context.setRequestConfig(builder.build());
return context;
}
});
client.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
});
return client;
}
use of org.apache.http.client.protocol.HttpClientContext in project ats-framework by Axway.
the class HttpClient method execute.
/**
* Main execute method that sends request and receives response.
*
* @param method The POST/PUT etc. method
* @return The response
* @throws HttpException
*/
private HttpResponse execute(HttpRequestBase httpMethod) throws HttpException {
HttpClientContext localContext = null;
if (httpClient == null) {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Add this interceptor to get the values of all HTTP headers in the request.
// Some of them are provided by the user while others are generated by Apache HTTP Components.
httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header[] requestHeaders = request.getAllHeaders();
actualRequestHeaders = new ArrayList<HttpHeader>();
for (Header header : requestHeaders) {
addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
}
if (debugLevel != HttpDebugLevel.NONE) {
logHTTPRequest(requestHeaders, request);
}
}
});
// Setup authentication
if (!StringUtils.isNullOrEmpty(username)) {
localContext = setupAuthentication(httpClientBuilder);
}
// Setup SSL
if (url.toLowerCase().startsWith("https")) {
setupSSL(httpClientBuilder);
}
// all important options are set, now build the HTTP client
if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {
HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClient = httpClientBuilder.setRoutePlanner(routePlanner).build();
} else {
httpClient = httpClientBuilder.build();
}
}
// Setup read and connect timeouts
httpMethod.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutSeconds * 1000).setConnectTimeout(connectTimeoutSeconds * 1000).build());
// Add HTTP headers
addHeadersToHttpMethod(httpMethod);
// Create response handler
ResponseHandler<HttpResponse> responseHandler = new ResponseHandler<HttpResponse>() {
@Override
public HttpResponse handleResponse(final org.apache.http.HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
Header[] responseHeaders = response.getAllHeaders();
List<HttpHeader> responseHeadersList = new ArrayList<HttpHeader>();
for (Header header : responseHeaders) {
addHeaderToList(responseHeadersList, header.getName(), header.getValue());
}
if ((debugLevel & HttpDebugLevel.HEADERS) == HttpDebugLevel.HEADERS) {
logHTTPResponse(responseHeaders, response);
}
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
// No response body, generally have '204 No content' status
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
if (responseBodyFilePath != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(responseBodyFilePath), false);
entity.writeTo(fos);
} finally {
IoUtils.closeStream(fos);
}
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList, bos.toByteArray());
}
}
} finally {
if (response instanceof CloseableHttpResponse) {
IoUtils.closeStream((CloseableHttpResponse) response, "Failed to close HttpResponse");
}
}
}
};
// Send the request as POST/GET etc. and return response.
try {
return httpClient.execute(httpMethod, responseHandler, localContext);
} catch (IOException e) {
throw new HttpException("Exception occurred sending message to URL '" + actualUrl + "' with a read timeout of " + readTimeoutSeconds + " seconds and a connect timeout of " + connectTimeoutSeconds + " seconds.", e);
} finally {
// clear internal variables
ActionLibraryConfigurator actionLibraryConfigurator = ActionLibraryConfigurator.getInstance();
if (!actionLibraryConfigurator.getHttpKeepRequestHeaders()) {
this.requestHeaders.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestParameters()) {
this.requestParameters.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestBody()) {
this.requestBody = null;
}
this.responseBodyFilePath = null;
}
}
Aggregations