Example usage for org.apache.http.conn.routing HttpRoute getTargetHost

List of usage examples for org.apache.http.conn.routing HttpRoute getTargetHost

Introduction

In this page you can find the example usage for org.apache.http.conn.routing HttpRoute getTargetHost.

Prototype

public final HttpHost getTargetHost() 

Source Link

Usage

From source file:org.apache.http.impl.execchain.ProtocolExec.java

void rewriteRequestURI(final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException {
    try {//w  ww .ja v a  2s . c  om
        URI uri = request.getURI();
        if (uri != null) {
            if (route.getProxyHost() != null && !route.isTunnelled()) {
                // Make sure the request URI is absolute
                if (!uri.isAbsolute()) {
                    final HttpHost target = route.getTargetHost();
                    uri = URIUtils.rewriteURI(uri, target, true);
                } else {
                    uri = URIUtils.rewriteURI(uri);
                }
            } else {
                // Make sure the request URI is relative
                if (uri.isAbsolute()) {
                    uri = URIUtils.rewriteURI(uri, null, true);
                } else {
                    uri = URIUtils.rewriteURI(uri);
                }
            }
            request.setURI(uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
}

From source file:org.apache.http.impl.execchain.ProtocolExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;/* w  ww .  jav a  2  s .c om*/
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    request.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(request, route);

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
            target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.apache.http.impl.execchain.RedirectExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final List<URI> redirectLocations = context.getRedirectLocations();
    if (redirectLocations != null) {
        redirectLocations.clear();// www.j ava  2 s  . c  o  m
    }

    final RequestConfig config = context.getRequestConfig();
    final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
    HttpRoute currentRoute = route;
    HttpRequestWrapper currentRequest = request;
    for (int redirectCount = 0;;) {
        final CloseableHttpResponse response = requestExecutor.execute(currentRoute, currentRequest, context,
                execAware);
        try {
            if (config.isRedirectsEnabled()
                    && this.redirectStrategy.isRedirected(currentRequest, response, context)) {

                if (redirectCount >= maxRedirects) {
                    throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
                }
                redirectCount++;

                final HttpRequest redirect = this.redirectStrategy.getRedirect(currentRequest, response,
                        context);
                if (!redirect.headerIterator().hasNext()) {
                    final HttpRequest original = request.getOriginal();
                    redirect.setHeaders(original.getAllHeaders());
                }
                currentRequest = HttpRequestWrapper.wrap(redirect);

                if (currentRequest instanceof HttpEntityEnclosingRequest) {
                    Proxies.enhanceEntity((HttpEntityEnclosingRequest) currentRequest);
                }

                final URI uri = currentRequest.getURI();
                final HttpHost newTarget = URIUtils.extractHost(uri);
                if (newTarget == null) {
                    throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
                }

                // Reset virtual host and auth states if redirecting to another host
                if (!currentRoute.getTargetHost().equals(newTarget)) {
                    final AuthState targetAuthState = context.getTargetAuthState();
                    if (targetAuthState != null) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                    final AuthState proxyAuthState = context.getProxyAuthState();
                    if (proxyAuthState != null) {
                        final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                        if (authScheme != null && authScheme.isConnectionBased()) {
                            this.log.debug("Resetting proxy auth state");
                            proxyAuthState.reset();
                        }
                    }
                }

                currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Redirecting to '" + uri + "' via " + currentRoute);
                }
                EntityUtils.consume(response.getEntity());
                response.close();
            } else {
                return response;
            }
        } catch (final RuntimeException ex) {
            response.close();
            throw ex;
        } catch (final IOException ex) {
            response.close();
            throw ex;
        } catch (final HttpException ex) {
            // Protocol exception related to a direct.
            // The underlying connection may still be salvaged.
            try {
                EntityUtils.consume(response.getEntity());
            } catch (final IOException ioex) {
                this.log.debug("I/O error while releasing connection", ioex);
            } finally {
                response.close();
            }
            throw ex;
        }
    }
}

From source file:org.apache.http.impl.execchain.RetryExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    final Header[] origheaders = request.getAllHeaders();
    for (int execCount = 1;; execCount++) {
        try {//  w w w. j  av  a  2 s .  com
            return this.requestExecutor.execute(route, request, context, execAware);
        } catch (final IOException ex) {
            if (execAware != null && execAware.isAborted()) {
                this.log.debug("Request has been aborted");
                throw ex;
            }
            if (retryHandler.retryRequest(ex, execCount, context)) {
                if (this.log.isInfoEnabled()) {
                    this.log.info("I/O exception (" + ex.getClass().getName()
                            + ") caught when processing request to " + route + ": " + ex.getMessage());
                }
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage(), ex);
                }
                if (!Proxies.isRepeatable(request)) {
                    this.log.debug("Cannot retry non-repeatable request");
                    throw new NonRepeatableRequestException(
                            "Cannot retry request " + "with a non-repeatable request entity", ex);
                }
                request.setHeaders(origheaders);
                if (this.log.isInfoEnabled()) {
                    this.log.info("Retrying request to " + route);
                }
            } else {
                if (ex instanceof NoHttpResponseException) {
                    final NoHttpResponseException updatedex = new NoHttpResponseException(
                            route.getTargetHost().toHostString() + " failed to respond");
                    updatedex.setStackTrace(ex.getStackTrace());
                    throw updatedex;
                } else {
                    throw ex;
                }
            }
        }
    }
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

@Override
public synchronized HttpRequest generateRequest() throws IOException, HttpException {
    final HttpRoute route = this.mainRequest.getRoute();
    if (!this.routeEstablished) {
        int step;
        do {//from w  w  w .j  ava2 s.c om
            final HttpRoute fact = this.managedConn.getRoute();
            step = this.routeDirector.nextStep(route, fact);
            switch (step) {
            case HttpRouteDirector.CONNECT_TARGET:
            case HttpRouteDirector.CONNECT_PROXY:
                break;
            case HttpRouteDirector.TUNNEL_TARGET:
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + this.id + "] Tunnel required");
                }
                final HttpRequest connect = createConnectRequest(route);
                this.currentRequest = wrapRequest(connect);
                this.currentRequest.setParams(this.params);
                break;
            case HttpRouteDirector.TUNNEL_PROXY:
                throw new HttpException("Proxy chains are not supported");
            case HttpRouteDirector.LAYER_PROTOCOL:
                managedConn.layerProtocol(this.localContext, this.params);
                break;
            case HttpRouteDirector.UNREACHABLE:
                throw new HttpException(
                        "Unable to establish route: " + "planned = " + route + "; current = " + fact);
            case HttpRouteDirector.COMPLETE:
                this.routeEstablished = true;
                break;
            default:
                throw new IllegalStateException("Unknown step indicator " + step + " from RouteDirector.");
            }
        } while (step > HttpRouteDirector.COMPLETE && this.currentRequest == null);
    }

    HttpHost target = (HttpHost) this.params.getParameter(ClientPNames.VIRTUAL_HOST);
    if (target == null) {
        target = route.getTargetHost();
    }
    final HttpHost proxy = route.getProxyHost();
    this.localContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
    this.localContext.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
    this.localContext.setAttribute(ExecutionContext.HTTP_CONNECTION, this.managedConn);
    this.localContext.setAttribute(ClientContext.ROUTE, route);

    if (this.currentRequest == null) {
        this.currentRequest = this.mainRequest.getRequest();

        final String userinfo = this.currentRequest.getURI().getUserInfo();
        if (userinfo != null) {
            this.targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
        }

        // Re-write request URI if needed
        rewriteRequestURI(this.currentRequest, route);
    }
    // Reset headers on the request wrapper
    this.currentRequest.resetHeaders();

    this.currentRequest.incrementExecCount();
    if (this.currentRequest.getExecCount() > 1 && !this.requestProducer.isRepeatable()
            && this.requestContentProduced) {
        throw new NonRepeatableRequestException(
                "Cannot retry request " + "with a non-repeatable request entity.");
    }
    this.execCount++;
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + this.id + "] Attempt " + this.execCount + " to execute request");
    }
    return this.currentRequest;
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

protected void rewriteRequestURI(final RequestWrapper request, final HttpRoute route) throws ProtocolException {
    try {/* w w w.ja  v a2  s.  c om*/
        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                final HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target);
                request.setURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null);
                request.setURI(uri);
            }
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
    }
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private HttpRequest createConnectRequest(final HttpRoute route) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers
    final HttpHost target = route.getTargetHost();
    final String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
        final AsyncSchemeRegistry registry = getSchemeRegistry(this.localContext);
        final AsyncScheme scheme = registry.getScheme(target.getSchemeName());
        port = scheme.getDefaultPort();//from  w  w  w  .  ja  v  a2s.  c  o  m
    }
    final StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));
    final ProtocolVersion ver = HttpProtocolParams.getVersion(this.params);
    final HttpRequest req = new BasicHttpRequest("CONNECT", buffer.toString(), ver);
    return req;
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private RoutedRequest handleRedirect() throws HttpException {
    if (this.redirectStrategy.isRedirected(this.currentRequest, this.currentResponse, this.localContext)) {

        final HttpRoute route = this.mainRequest.getRoute();
        final RequestWrapper request = this.mainRequest.getRequest();

        final int maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
        if (this.redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }/*from   w w w. j a  v a2  s  .  co m*/
        this.redirectCount++;

        final HttpUriRequest redirect = this.redirectStrategy.getRedirect(this.currentRequest,
                this.currentResponse, this.localContext);
        final HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        final URI uri = redirect.getURI();
        if (uri.getHost() == null) {
            throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
        }
        final HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Reset auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + this.id + "] Resetting target auth state");
            }
            this.targetAuthState.reset();
            final AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + this.id + "] Resetting proxy auth state");
                }
                this.proxyAuthState.reset();
            }
        }

        final RequestWrapper newRequest = wrapRequest(redirect);
        newRequest.setParams(this.params);

        final HttpRoute newRoute = determineRoute(newTarget, newRequest, this.localContext);

        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + this.id + "] Redirecting to '" + uri + "' via " + newRoute);
        }
        return new RoutedRequest(newRequest, newRoute);
    }
    return null;
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private RoutedRequest handleTargetChallenge(final CredentialsProvider credsProvider) throws HttpException {
    final HttpRoute route = this.mainRequest.getRoute();
    HttpHost target = (HttpHost) this.localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (target == null) {
        target = route.getTargetHost();
    }// w w w .  j  av  a2s  .  c  om
    if (this.authenticator.isAuthenticationRequested(target, this.currentResponse, this.targetAuthStrategy,
            this.targetAuthState, this.localContext)) {
        if (this.authenticator.authenticate(target, this.currentResponse, this.targetAuthStrategy,
                this.targetAuthState, this.localContext)) {
            // Re-try the same request via the same route
            return this.mainRequest;
        }
        return null;
    }
    return null;
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

@Override
public void responseCompleted(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpResponse currentResponse = handler.getCurrentResponse();

    if (!handler.isRouteEstablished()) {
        final int status = currentResponse.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            handler.setCurrentResponse(null);
            return;
        }//  w w  w.ja  va 2 s.c  o m
    }

    final boolean keepAlive = handler.manageConnectionPersistence();
    if (!keepAlive) {
        handler.releaseConnection();
        final AuthState proxyAuthState = localContext.getProxyAuthState();
        if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null
                && proxyAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
            }
            proxyAuthState.reset();
        }
        final AuthState targetAuthState = localContext.getTargetAuthState();
        if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null
                && targetAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
            }
            targetAuthState.reset();
        }
    }

    Object userToken = localContext.getUserToken();
    if (userToken == null) {
        userToken = this.userTokenHandler.getUserToken(localContext);
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
    }

    if (state.getFinalResponse() != null) {
        final HttpAsyncResponseConsumer<?> responseConsumer = state.getResponseConsumer();
        responseConsumer.responseCompleted(localContext);
        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + state.getId() + "] Response processed");
        }
        handler.releaseConnection();
    } else {
        if (state.getRedirect() != null) {
            final HttpUriRequest redirect = state.getRedirect();
            final URI uri = redirect.getURI();
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Redirecting to '" + uri + "'");
            }
            state.setRedirect(null);

            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }

            // Reset auth states if redirecting to another host
            final HttpRoute route = handler.getRoute();
            if (!route.getTargetHost().equals(newTarget)) {
                final AuthState targetAuthState = localContext.getTargetAuthState();
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
                }
                targetAuthState.reset();
                final AuthState proxyAuthState = localContext.getProxyAuthState();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
                    }
                    proxyAuthState.reset();
                }
            }

            if (!redirect.headerIterator().hasNext()) {
                final HttpRequest original = state.getMainRequest().getOriginal();
                redirect.setHeaders(original.getAllHeaders());
            }

            final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(redirect);
            final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, newRequest, localContext);
            if (!route.equals(newRoute)) {
                handler.releaseConnection();
            }
            handler.setRoute(newRoute);
            handler.setCurrentRequest(newRequest);
            state.setMainRequest(newRequest);
            prepareRequest(state, handler);
        }
    }
    handler.setCurrentResponse(null);
}