Search in sources :

Example 6 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project jersey by jersey.

the class ApacheConnector method apply.

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);
    try {
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());
        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }
        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }
            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IOException(java.io.IOException) URI(java.net.URI) ProcessingException(javax.ws.rs.ProcessingException) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Header(org.apache.http.Header) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Example 7 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project opennms by OpenNMS.

the class HttpClientWrapper method enablePreemptiveAuth.

protected void enablePreemptiveAuth(final HttpClientBuilder builder) {
    /**
         * Add an HttpRequestInterceptor that will perform preemptive authentication
         * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
         */
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (context instanceof HttpClientContext) {
                final HttpClientContext clientContext = (HttpClientContext) context;
                final AuthState authState = clientContext.getTargetAuthState();
                final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
                final HttpHost targetHost = clientContext.getTargetHost();
                // If not authentication scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.update(new BasicScheme(), creds);
                    }
                }
            } else {
                throw new IllegalArgumentException("Not sure how to handle a non-HttpClientContext context.");
            }
        }
    };
    builder.addInterceptorFirst(preemptiveAuth);
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthState(org.apache.http.auth.AuthState) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) HttpContext(org.apache.http.protocol.HttpContext) AuthScope(org.apache.http.auth.AuthScope) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 8 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project opennms by OpenNMS.

the class ScvEnabledRestClientImpl method getResponse.

// Setup a client with pre-emptive authentication
private CloseableHttpResponse getResponse(HttpGet httpget) throws Exception {
    CloseableHttpResponse response = null;
    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), getCredentials());
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    response = httpclient.execute(target, httpget, localContext);
    return response;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthScope(org.apache.http.auth.AuthScope) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache)

Example 9 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project orientdb by orientechnologies.

the class BaseHttpTest method exec.

protected BaseHttpTest exec() throws IOException {
    final HttpHost targetHost = new HttpHost(getHost(), getPort(), getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(getUserName(), getUserPassword()));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    if (keepAlive != null)
        request.addHeader("Connection", keepAlive ? "Keep-Alive" : "Close");
    if (payload != null && request instanceof HttpEntityEnclosingRequestBase)
        ((HttpEntityEnclosingRequestBase) request).setEntity(payload);
    final CloseableHttpClient httpClient = HttpClients.createDefault();
    // DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(retry, false);
    // context.setAttribute(HttpMethodParams.RETRY_HANDLER, retryhandler);
    response = httpClient.execute(targetHost, request, context);
    return this;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AuthCache(org.apache.http.client.AuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 10 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project calcite-avatica by apache.

the class AvaticaCommonsHttpClientSpnegoImpl method send.

@Override
public byte[] send(byte[] request) {
    HttpClientContext context = HttpClientContext.create();
    context.setTargetHost(host);
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);
    ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);
    // Create the client with the AuthSchemeRegistry and manager
    HttpPost post = new HttpPost(toURI(url));
    post.setEntity(entity);
    try (CloseableHttpResponse response = client.execute(post, context)) {
        final int statusCode = response.getStatusLine().getStatusCode();
        if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
            return EntityUtils.toByteArray(response.getEntity());
        }
        throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        LOG.debug("Failed to execute HTTP request", e);
        throw new RuntimeException(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) URISyntaxException(java.net.URISyntaxException)

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