Handle redirection responses
163340
private function handleRedirect(ResponseInterface $response): ResponseInterface
    {
        if ($this->debugbar->isDataPersisted() || session_status() === PHP_SESSION_ACTIVE) {
            $this->debugbar->stackData();
        }

        return $response;
    }
918458
private boolean processRedirectResponse(final HttpMethod method)
     throws RedirectException {
		//get the location header to find out where to redirect to
		Header locationHeader = method.getResponseHeader("location");
		if (locationHeader == null) {
			// got a redirect response, but no location header
			LOG.error("Received redirect response " + method.getStatusCode()
					+ " but no location header");
			return false;
		}
		String location = locationHeader.getValue();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Redirect requested to location '" + location + "'");
		}
        
		//rfc2616 demands the location value be a complete URI
		//Location       = "Location" ":" absoluteURI
		URI redirectUri = null;
		URI currentUri = null;

		try {
			currentUri = new URI(
				this.conn.getProtocol().getScheme(),
				null,
                this.conn.getHost(), 
                this.conn.getPort(), 
				method.getPath()
			);
			
            String charset = method.getParams().getUriCharset();
            redirectUri = new URI(location, true, charset);
			
            if (redirectUri.isRelativeURI()) {
				if (this.params.isParameterTrue(HttpClientParams.REJECT_RELATIVE_REDIRECT)) {
					LOG.warn("Relative redirect location '" + location + "' not allowed");
					return false;
				} else { 
					//location is incomplete, use current values for defaults
					LOG.debug("Redirect URI is not absolute - parsing as relative");
					redirectUri = new URI(currentUri, redirectUri);
				}
			} else {
                // Reset the default params
                method.getParams().setDefaults(this.params);
            }
            method.setURI(redirectUri);
            hostConfiguration.setHost(redirectUri);
		} catch (URIException ex) {
            throw new InvalidRedirectLocationException(
                    "Invalid redirect location: " + location, location, ex);
		}

        if (this.params.isParameterFalse(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS)) {
            if (this.redirectLocations == null) {
                this.redirectLocations = new HashSet<URI>();
            }
            this.redirectLocations.add(currentUri);
            try {
                if(redirectUri.hasQuery()) {
                    redirectUri.setQuery(null);
                }
            } catch (URIException e) {
                // Should never happen
                return false;
            }

            if (this.redirectLocations.contains(redirectUri)) {
                throw new CircularRedirectException("Circular redirect to '" +
                    redirectUri + "'");
            }
        }

		if (LOG.isDebugEnabled()) {
			LOG.debug("Redirecting from '" + currentUri.getEscapedURI()
				+ "' to '" + redirectUri.getEscapedURI());
		}
        //And finally invalidate the actual authentication scheme
                method.getHostAuthState().invalidate(); 
                method.getProxyAuthState().invalidate(); 
		return true;
	}
1008890
def get_redirect_target(self, resp):
        """"""
        # Due to the nature of how requests processes redirects this method will
        # be called at least once upon the original response and at least twice
        # on each subsequent redirect response (if any).
        # If a custom mixin is used to handle this logic, it may be advantageous
        # to cache the redirect location onto the response object as a private
        # attribute.
        if resp.is_redirect:
            location = resp.headers['location']
            # Currently the underlying http module on py3 decode headers
            # in latin1, but empirical evidence suggests that latin1 is very
            # rarely used with non-ASCII characters in HTTP headers.
            # It is more likely to get UTF8 header rather than latin1.
            # This causes incorrect handling of UTF8 encoded location headers.
            # To solve this, we re-encode the location in latin1.
            if is_py3:
                location = location.encode('latin1')
            return to_native_string(location, 'utf8')
        return None
591530
public static void sendRedirect(
		HttpServletResponse response,
		String location,
		int status
	) throws IllegalStateException, IOException {
		// Response must not be committed
		if(response.isCommitted()) throw new IllegalStateException("Unable to redirect: Response already committed");

		response.setHeader("Location", location);
		response.sendError(status);
	}
1349810
def _process_response(self, response: Response):
        ''''''
        _logger.debug('Handling response')

        self._redirect_tracker.load(response)

        if self._redirect_tracker.is_redirect():
            self._process_redirect()
            self._loop_type = LoopType.redirect
        elif response.status_code == http.client.UNAUTHORIZED and self._next_request.password:
            self._process_authentication(response)
        else:
            self._next_request = None
            self._loop_type = LoopType.normal

        if self._cookie_jar:
            self._extract_cookies(response)

            if self._next_request:
                self._add_cookies(self._next_request)
1155303
def resolve_redirects(self, resp, req, stream=False, timeout=None,
                          verify=True, cert=None, proxies=None):
        """"""

        i = 0
        hist = [] # keep track of history

        while resp.is_redirect:
            prepared_request = req.copy()

            if i > 0:
                # Update history and keep track of redirects.
                hist.append(resp)
                new_hist = list(hist)
                resp.history = new_hist

            try:
                resp.content  # Consume socket so it can be released
            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
                resp.raw.read(decode_content=False)

            if i >= self.max_redirects:
                raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)

            # Release the connection back into the pool.
            resp.close()

            url = resp.headers['location']
            method = req.method

            # Handle redirection without scheme (see: RFC 1808 Section 4)
            if url.startswith('//'):
                parsed_rurl = urlparse(resp.url)
                url = '%s:%s' % (parsed_rurl.scheme, url)

            # The scheme should be lower case...
            parsed = urlparse(url)
            url = parsed.geturl()

            # Facilitate relative 'location' headers, as allowed by RFC 7231.
            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
            # Compliant with RFC3986, we percent encode the url.
            if not parsed.netloc:
                url = urljoin(resp.url, requote_uri(url))
            else:
                url = requote_uri(url)

            prepared_request.url = to_native_string(url)
            # Cache the url, unless it redirects to itself.
            if resp.is_permanent_redirect and req.url != prepared_request.url:
                self.redirect_cache[req.url] = prepared_request.url

            # http://tools.ietf.org/html/rfc7231#section-6.4.4
            if (resp.status_code == codes.see_other and
                    method != 'HEAD'):
                method = 'GET'

            # Do what the browsers do, despite standards...
            # First, turn 302s into GETs.
            if resp.status_code == codes.found and method != 'HEAD':
                method = 'GET'

            # Second, if a POST is responded to with a 301, turn it into a GET.
            # This bizarre behaviour is explained in Issue 1704.
            if resp.status_code == codes.moved and method == 'POST':
                method = 'GET'

            prepared_request.method = method

            # https://github.com/kennethreitz/requests/issues/1084
            if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
                if 'Content-Length' in prepared_request.headers:
                    del prepared_request.headers['Content-Length']

                prepared_request.body = None

            headers = prepared_request.headers
            try:
                del headers['Cookie']
            except KeyError:
                pass

            # Extract any cookies sent on the response to the cookiejar
            # in the new request. Because we've mutated our copied prepared
            # request, use the old one that we haven't yet touched.
            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
            prepared_request._cookies.update(self.cookies)
            prepared_request.prepare_cookies(prepared_request._cookies)

            # Rebuild auth and proxy information.
            proxies = self.rebuild_proxies(prepared_request, proxies)
            self.rebuild_auth(prepared_request, resp)

            # Override the original request.
            req = prepared_request

            resp = self.send(
                req,
                stream=stream,
                timeout=timeout,
                verify=verify,
                cert=cert,
                proxies=proxies,
                allow_redirects=False,
            )

            extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)

            i += 1
            yield resp
1210967
public static void redirect(HttpServletRequest request, HttpServletResponse response,
                               String url) throws IOException {
        String redirectUrl;

        if (url.startsWith("/")) {
            redirectUrl = request.getContextPath() + url;
        } else {
            redirectUrl = url;
        }

        logger.debug("Redirecting to URL: {}", redirectUrl);

        response.sendRedirect(redirectUrl);
    }
1211644
private void handleRenderRedirect(final PrintWriter writer) {
		UIContext uic = UIContextHolder.getCurrent();
		// Redirect user to error page
		LOG.warn("User will be redirected to " + redirectUrl);

		// Setup response with redirect
		getResponse().setContentType(WebUtilities.CONTENT_TYPE_XML);
		writer.write(XMLUtil.getXMLDeclarationWithThemeXslt(uic));

		writer.print("<ui:ajaxresponse ");
		writer.print(XMLUtil.UI_NAMESPACE);
		writer.print(">");
		writer.print("<ui:ajaxtarget id=\"" + triggerId + "\" action=\"replace\">");

		// Redirect URL
		writer.print("<ui:redirect url=\"" + redirectUrl + "\" />");

		writer.print("</ui:ajaxtarget>");
		writer.print("</ui:ajaxresponse>");
	}
574359
def redirect(location, code=302, **kw):
    """"""
    if not 300 <= code < 400:
        raise ValueError("Not a 3xx status code: '%s'" % code)
    return response(code=code, location=location, **kw)
222329
def get_response(self, request):
        ''''''
        # the redirect key is already placed in the response by HttpResponseJavascriptRedirect
        return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, **self.kwargs)
932292
def _raise_redirect_exceptions(response):
    
    if response.status_code not in [301, 302, 307]:
        return None
    new_url = urljoin(response.url, response.headers['location'])
    if 'reddits/search' in new_url:  # Handle non-existent subreddit
        subreddit = new_url.rsplit('=', 1)[1]
        raise InvalidSubreddit('`{0}` is not a valid subreddit'
                               .format(subreddit))
    elif not RE_REDIRECT.search(response.url):
        raise RedirectException(response.url, new_url)
    return new_url
335322
def _handle_command_response(self, res, event):
        

        response_handler = None

        if isinstance(res, basestring):
            response_handler = functools.partial(self._send_rtm_message, event['channel'])
        elif isinstance(res, dict):
            response_handler = self._send_api_message

        if response_handler is not None:
            response_handler(res)
149061
def _handle_response(response):
        
        if not response.ok:
            raise NeverBounceAPIError(response)
        if response.headers.get('Content-Type') == 'application/octet-stream':
            return response.iter_lines()

        try:
            resp = response.json()
        except ValueError:
             raise InvalidResponseError('Failed to handle the response content-type {}.'.format(
                 response.headers.get('Content-Type'))
             )
        if 'success' in resp and not resp['success']:
            if 'msg' in resp and resp['msg'] == 'Authentication failed':
                raise AccessTokenExpired
            else:
                raise NeverBounceAPIError(response)
        return resp
395252
function response(txn, res, next) {
        if (!txn.redirectURI) {
            return next(new Error('Unable to issue redirect for OAuth 2.0 transaction'));
        }
        if (!txn.res.allow) {
            var err = {};
            err.error = 'access_denied';
            if (txn.req && txn.req.state) {
                err.state = txn.req.state;
            }

            var parsed = url.parse(txn.redirectURI);
            parsed.hash = qs.stringify(err);

            var location = url.format(parsed);
            return res.redirect(location);
        }

        function issued(err, accessToken, params) {
            if (err) {
                return next(err);
            }
            if (!accessToken) {
                return next(new AuthorizationError('Request denied by authorization server', 'access_denied'));
            }

            var tok = {};
            tok.access_token = accessToken;
            if (params) {
                utils.merge(tok, params);
            }
            tok.token_type = tok.token_type || 'Bearer';
            if (txn.req && txn.req.state) {
                tok.state = txn.req.state;
            }

            var parsed = url.parse(txn.redirectURI);
            parsed.hash = qs.stringify(tok);

            var location = url.format(parsed);
            return res.redirect(location);
        }

        // NOTE: In contrast to an authorization code grant, redirectURI is not
        //       passed as an argument to the issue callback because it is not used
        //       as a verifier in a subsequent token exchange.  However, when
        //       issuing an implicit access tokens, an application must ensure that
        //       the redirection URI is registered, which can be done in the
        //       `validate` callback of `authorization` middleware.

        try {
            var arity = issue.length;
            if (arity === 5) {
                issue(txn.client, txn.user, txn.req.scope, txn.res, issued);
            } else { // arity == 4
                issue(txn.client, txn.user, txn.req.scope, issued);
            }
        } catch (ex) {
            return next(ex);
        }
    }
1372227
def process_response(self, request, response):
        

        if request.is_ajax() and hasattr(request, 'horizon'):
            queued_msgs = request.horizon['async_messages']
            if type(response) == http.HttpResponseRedirect:
                # Drop our messages back into the session as per usual so they
                # don't disappear during the redirect. Not that we explicitly
                # use django's messages methods here.
                for tag, message, extra_tags in queued_msgs:
                    getattr(django_messages, tag)(request, message, extra_tags)
                # if response['location'].startswith(settings.LOGOUT_URL):
                #     redirect_response = http.HttpResponse(status=401)
                #     # This header is used for handling the logout in JS
                #     redirect_response['logout'] = True
                #     if self.logout_reason is not None:
                #         utils.add_logout_reason(
                #             request, redirect_response, self.logout_reason)
                # else:
                redirect_response = http.HttpResponse()
                # Use a set while checking if we want a cookie's attributes
                # copied
                cookie_keys = set(('max_age', 'expires', 'path', 'domain',
                                   'secure', 'httponly', 'logout_reason'))
                # Copy cookies from HttpResponseRedirect towards HttpResponse
                for cookie_name, cookie in six.iteritems(response.cookies):
                    cookie_kwargs = dict((
                        (key, value) for key, value in six.iteritems(cookie)
                        if key in cookie_keys and value
                    ))
                    redirect_response.set_cookie(
                        cookie_name, cookie.value, **cookie_kwargs)
                redirect_response['X-Horizon-Location'] = response['location']
                upload_url_key = 'X-File-Upload-URL'
                if upload_url_key in response:
                    self.copy_headers(response, redirect_response,
                                      (upload_url_key, 'X-Auth-Token'))
                return redirect_response
            if queued_msgs:
                # TODO(gabriel): When we have an async connection to the
                # client (e.g. websockets) this should be pushed to the
                # socket queue rather than being sent via a header.
                # The header method has notable drawbacks (length limits,
                # etc.) and is not meant as a long-term solution.
                response['X-Horizon-Messages'] = json.dumps(queued_msgs)
        return response
693660
function handleResponse(done, err, response, body) {
  if (err) return done(err, null);
  if (response.statusCode !== 200) return done(new Error(body.msg || 'Unknown error'), null);

  done(null, body);
}
1078280
@Override
    public boolean handleExecutionOutcome(
            FlowExecutionOutcome outcome, ActionRequest request, ActionResponse response) {
        if (this.redirectOnEnd != null) {
            final String redirectPath = request.getContextPath() + this.redirectOnEnd;
            try {
                response.sendRedirect(redirectPath);
                return true;
            } catch (IOException e) {
                this.logger.warn("Failed to send flow-end redirect to '" + redirectPath + "'");
            }
        }

        return false;
    }