Search in sources :

Example 21 with HttpClientContext

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);
        }
    }
}
Also used : Header(org.apache.http.Header) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) URI(java.net.URI)

Example 22 with HttpClientContext

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));
        }
    });
}
Also used : HttpResponse(org.apache.http.HttpResponse) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) HttpHost(org.apache.http.HttpHost) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 23 with HttpClientContext

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
            }
        }
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) Message(org.apache.camel.Message) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) IOException(java.io.IOException) Exchange(org.apache.camel.Exchange) Header(org.apache.http.Header) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 24 with HttpClientContext

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;
}
Also used : DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) Builder(org.apache.http.client.config.RequestConfig.Builder) RestTemplate(org.springframework.web.client.RestTemplate) HttpContext(org.apache.http.protocol.HttpContext) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) IOException(java.io.IOException) URI(java.net.URI) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) HttpMethod(org.springframework.http.HttpMethod)

Example 25 with HttpClientContext

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;
    }
}
Also used : ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) ActionLibraryConfigurator(com.axway.ats.action.ActionLibraryConfigurator) ArrayList(java.util.ArrayList) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Header(org.apache.http.Header) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)41 IOException (java.io.IOException)16 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)16 HttpHost (org.apache.http.HttpHost)14 AuthScope (org.apache.http.auth.AuthScope)14 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 CredentialsProvider (org.apache.http.client.CredentialsProvider)11 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 HttpGet (org.apache.http.client.methods.HttpGet)10 BasicScheme (org.apache.http.impl.auth.BasicScheme)10 HttpResponse (org.apache.http.HttpResponse)9 AuthCache (org.apache.http.client.AuthCache)9 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)9 Header (org.apache.http.Header)8 URI (java.net.URI)6 HttpEntity (org.apache.http.HttpEntity)6 HttpContext (org.apache.http.protocol.HttpContext)4 SocketTimeoutException (java.net.SocketTimeoutException)3 URISyntaxException (java.net.URISyntaxException)3