Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext setAttribute.

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * Configure the UserToken so that the SSL context is reused
 * See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
 * @param localContext {@link HttpContext}
 *///  w  w  w  .j  a v a 2s.c  o  m
private void setupClientContextBeforeSample(HttpContext localContext) {
    Object userToken = null;
    // During recording JMeterContextService.getContext().getVariables() is null
    JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
    if (jMeterVariables != null) {
        userToken = jMeterVariables.getObject(USER_TOKEN);
    }
    if (userToken != null) {
        if (log.isDebugEnabled()) {
            log.debug("Found user token:" + userToken + " as JMeter variable:" + USER_TOKEN
                    + ", storing it in HttpContext");
        }
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
    } else {
        // It would be better to create a ClientSessionManager that would compute this value
        // for now it can be Thread.currentThread().getName() but must be changed when we would change 
        // the Thread per User model
        String userId = Thread.currentThread().getName();
        if (log.isDebugEnabled()) {
            log.debug("Storing in HttpContext the user token:" + userId);
        }
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userId);
    }
}

From source file:com.tandong.sa.aq.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }//from   w ww.ja  va2s  .  c  om

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = client.execute(hr, context);

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);

    File file = null;

    if (code < 200 || code >= 300) {

        try {

            if (entity != null) {

                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.androidquery.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }//from  w w w  . j a  va2 s  .  co  m

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = null;

    try {
        response = client.execute(hr, context);
    } catch (HttpHostConnectException e) {

        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            response = client.execute(hr, context);
        } else {
            throw e;
        }
    }

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    File file = null;

    if (code < 200 || code >= 300) {

        InputStream is = null;

        try {

            if (entity != null) {

                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }/*from  w  w  w  . j a  v  a 2  s .  c o m*/

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = null;

    try {
        //response = client.execute(hr, context);
        response = execute(hr, client, context);
    } catch (HttpHostConnectException e) {

        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            //response = client.execute(hr, context);
            response = execute(hr, client, context);
        } else {
            throw e;
        }
    }

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    File file = null;

    if (code < 200 || code >= 300) {

        InputStream is = null;

        try {

            if (entity != null) {

                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            is = entity.getContent();
            if ("gzip".equalsIgnoreCase(getEncoding(entity))) {
                is = new GZIPInputStream(is);
            }

            copy(is, os, (int) entity.getContentLength());

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.amos.tool.SelfRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }/*from  w  w  w . j  a va2  s .c o  m*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location.replaceAll(" ", "%20"));

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}

From source file:spaceRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }//from  ww w  . j  av a  2s. co  m
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue().replaceAll(" ", "%20");
    ;
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            //redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:clj_httpc.CustomRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*from  w  w  w  .ja  v a 2 s. c  o m*/
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        CustomRedirectLocations redirectLocations = (CustomRedirectLocations) context
                .getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new CustomRedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            int statusCode = response.getStatusLine().getStatusCode();
            redirectLocations.add(redirectURI, statusCode);
        }
    }

    return uri;
}

From source file:com.mongolduu.android.ng.misc.RedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*from  w w w .  j  ava  2 s  .  co m*/
    // get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    // HERE IS THE MODIFIED LINE OF CODE
    String location = locationHeader.getValue().replaceAll(" ", "%20");

    URI uri;
    try {
        uri = new URI(location);
    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:com.amytech.android.library.utils.asynchttp.MyRedirectHandler.java

@Override
public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }//from w ww.j  a v a2  s  .co  m
    // get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    // HERE IS THE MODIFIED LINE OF CODE
    String location = locationHeader.getValue().replaceAll(" ", "%20");

    URI uri;
    try {
        uri = new URI(location);
    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}