When the browser hits the redirect URL, use the provided code to ask Slack for a session.
160811
@Override public MockResponse dispatch(RecordedRequest request) {
    HttpUrl requestUrl = mockWebServer.url(request.getPath());
    String code = requestUrl.queryParameter("code");
    String stateString = requestUrl.queryParameter("state");
    ByteString state = stateString != null ? ByteString.decodeBase64(stateString) : null;

    Listener listener;
    synchronized (this) {
      listener = listeners.get(state);
    }

    if (code == null || listener == null) {
      return new MockResponse()
          .setResponseCode(404)
          .setBody("unexpected request");
    }

    try {
      OAuthSession session = slackApi.exchangeCode(code, redirectUrl());
      listener.sessionGranted(session);
    } catch (IOException e) {
      return new MockResponse()
          .setResponseCode(400)
          .setBody("code exchange failed: " + e.getMessage());
    }

    synchronized (this) {
      listeners.remove(state);
    }

    // Success!
    return new MockResponse()
        .setResponseCode(302)
        .addHeader("Location", "https://twitter.com/CuteEmergency/status/789457462864863232");
  }
674696
def get_access_token(self, code, state=None):
        '''
        
        '''
        kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
        if self._redirect_uri:
            kw['redirect_uri'] = self._redirect_uri
        if state:
            kw['state'] = state
        opener = build_opener(HTTPSHandler)
        request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))
        request.get_method = _METHOD_MAP['POST']
        request.add_header('Accept', 'application/json')
        try:
            response = opener.open(request, timeout=TIMEOUT)
            r = _parse_json(response.read())
            if 'error' in r:
                raise ApiAuthError(str(r.error))
            return str(r.access_token)
        except HTTPError as e:
            raise ApiAuthError('HTTPError when get access token')
1173975
def redirect(self, url):
        """"""
        url = '{}/view'.format(url)
        return self.request.response.redirect(url)
643861
def request(self, method, url, **kwargs):
        
        resp = super(CookieSession, self).request(method, url, **kwargs)

        if not self._auto_renew:
            return resp

        is_expired = any((
            resp.status_code == 403 and
            response_to_json_dict(resp).get('error') == 'credentials_expired',
            resp.status_code == 401
        ))

        if is_expired:
            self.login()
            resp = super(CookieSession, self).request(method, url, **kwargs)

        return resp
687906
def default_redirect(request, fallback_url, **kwargs):
    
    redirect_field_name = kwargs.get("redirect_field_name", "next")
    next = request.POST.get(redirect_field_name,
                            request.GET.get(redirect_field_name, ''))
    if not next:
        # try the session if available
        if hasattr(request, "session"):
            session_key_value = kwargs.get("session_key_value", "redirect_to")
            next = request.session.get(session_key_value)
    is_safe = functools.partial(
        ensure_safe_url,
        allowed_protocols=kwargs.get("allowed_protocols"),
        allowed_host=request.get_host()
    )
    redirect_to = next if next and is_safe(next) else fallback_url
    # perform one last check to ensure the URL is safe to redirect to. if it
    # is not then we should bail here as it is likely developer error and
    # they should be notified
    is_safe(redirect_to, raise_on_fail=True)
    return redirect_to
134983
def switch_state(request):
    

    if request.session.get(SESSION_KEY):
        request.session[SESSION_KEY] = False
    else:
        request.session[SESSION_KEY] = True

    # Get redirect location
    # Don't go to non local paths
    url = request.GET.get('redirect_to', '/')
    if url.startswith('http'):
        url = '/'
    return redirect(url)
26837
async def call(self, method, **params):
        
        url = self.SLACK_RPC_PREFIX + method
        data = FormData()
        data.add_fields(MultiDict(token=self.bot_token, charset='utf-8', **params))
        response_body = await self.request(
            method='POST',
            url=url,
            data=data
        )
        if 'warning' in response_body:
            logger.warning(f'Warnings received from API call {method}: {response_body["warning"]}')
        if 'ok' not in response_body:
            logger.error(f'No ok marker in slack API call {method} {params} => {response_body}')
            raise SlackCallException('There is no ok marker, ... strange', method=method)
        if not response_body['ok']:
            logger.error(f'Slack API call failed {method} {params} => {response_body}')
            raise SlackCallException(f'No OK response returned', method=method)
        return response_body
1064930
def _ensure_html_response(url, session):
    # type: (str, PipSession) -> None
    
    scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
    if scheme not in {'http', 'https'}:
        raise _NotHTTP()

    resp = session.head(url, allow_redirects=True)
    resp.raise_for_status()

    _ensure_html_header(resp)
948128
def Call(method,url,payload=None,session=None,debug=False):
		
		if session is not None:
			token = session['token']
			http_session = session['http_session']

		else:
			if not clc._LOGIN_TOKEN_V2:
				API._Login()
			token = clc._LOGIN_TOKEN_V2
			http_session = clc._REQUESTS_SESSION

		if payload is None:
		    payload = {}

		# If executing refs provided in API they are abs paths,
		# Else refs we build in the sdk are relative
		if url[0]=='/':  fq_url = "%s%s" % (clc.defaults.ENDPOINT_URL_V2,url)
		else:  fq_url = "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,url)

		http_session.headers.update({'Authorization': "Bearer %s" % token})

		if isinstance(payload, basestring):  http_session.headers['content-type'] = "Application/json" # added for server ops with str payload
		else:  http_session.headers['content-type'] = "application/x-www-form-urlencoded"

		if method=="GET":
			r = http_session.request(method,fq_url,
			                     params=payload,
								 verify=API._ResourcePath('clc/cacert.pem'))
		else:
			r = http_session.request(method,fq_url,
			                     data=payload,
								 verify=API._ResourcePath('clc/cacert.pem'))

		if debug:
			API._DebugRequest(request=requests.Request(method,fq_url,data=payload,headers=http_session.headers).prepare(),
			                  response=r)

		if r.status_code>=200 and r.status_code<300:
			try:
				return(r.json())
			except:
				return({})
		else:
			try:
				e = clc.APIFailedResponse("Response code %s.  %s %s %s" %
				                          (r.status_code,r.json()['message'],method,fq_url))
				e.response_status_code = r.status_code
				e.response_json = r.json()
				e.response_text = r.text
				raise(e)
			except clc.APIFailedResponse:
				raise
			except:
				e = clc.APIFailedResponse("Response code %s. %s. %s %s" %
				                         (r.status_code,r.text,method,fq_url))
				e.response_status_code = r.status_code
				e.response_json = {}	# or should this be None?
				e.response_text = r.text
				raise(e)
69948
def do_http(uri, request)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      # Let then know about us
      request['User-Agent'] = 'SlackRubyAPIWrapper'
      begin
        http.request(request)
      rescue OpenSSL::SSL::SSLError => e
        raise Slack::Error, 'SSL error connecting to Slack.'
      end
    end
590391
def request_user_auth(code, redirect_uri)
      response = http_client(MXIT_AUTH_TOKEN_URI) do |http, path|

        request = new_post_request(path, {
          "grant_type" => "authorization_code",
          "code" => code,
          "redirect_uri" => redirect_uri
        })

        http.request(request)
      end

      @auth_token = AuthToken.new(handle_response(response))
    end
1125841
def redirect(url, code=303):
    
    scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
    location = urljoin(request.url, urljoin(scriptname, url))
    raise HTTPResponse("", status=code, header=dict(Location=location))
729829
public function redirect($url, $useUrl = true, $httpCode = 302)
    {
        Atomik::fireEvent('Atomik::Redirect', array(&$url, &$useUrl, &$httpCode));
        if ($url === false) {
            return;
        }
        
        if ($useUrl) {
            $url = Atomik::url($url);
        }
        
        if (isset($_SESSION)) {
            $session = $_SESSION;
            // seems to prevent a php bug with session before redirections
            session_regenerate_id(true);
            $_SESSION = $session;
            // avoid loosing the session
            session_write_close();
        }
        
        header('Location: ' . $url, true, $httpCode);
        Atomik::end(true, false);
    }
760982
private void handleRequestRedirect(
            final CrawlCandidate currentCrawlCandidate,
            final String redirectedUrl) {
        CrawlRequestBuilder builder = new CrawlRequestBuilder(redirectedUrl)
                .setPriority(currentCrawlCandidate.getPriority());
        currentCrawlCandidate.getMetadata().ifPresent(builder::setMetadata);
        CrawlRequest redirectedRequest = builder.build();

        crawlFrontier.feedRequest(redirectedRequest, false);
        callbackManager.call(CrawlEvent.REQUEST_REDIRECT,
                new RequestRedirectEvent(currentCrawlCandidate, redirectedRequest));
    }
1263389
def request_access_token(self, code, redirect_uri=None):
        '''
        
        '''
        redirect = redirect_uri or self._redirect_uri
        resp_text = _http('POST', 'https://api.weibo.com/oauth2/access_token',
                          client_id=self._client_id, client_secret=self._client_secret,
                          redirect_uri=redirect, code=code, grant_type='authorization_code')
        r = _parse_json(resp_text)
        current = int(time.time())
        expires = r.expires_in + current
        remind_in = r.get('remind_in', None)
        if remind_in:
            rtime = int(remind_in) + current
            if rtime < expires:
                expires = rtime
        return JsonDict(access_token=r.access_token, expires=expires, uid=r.get('uid', None))
823377
def getURIWithRedirect(self, url):
        ''''''
        tries = 0
        while tries < 5:
                conn = httplib.HTTPConnection(self.server)
                conn.request("GET", url)
                r1 = conn.getresponse()
                if r1.status in [301, 302, 303, 307]:
                    location = r1.getheader('Location')
                    if self.debug:
                        print("redirect from %s to %s" % (url, location))
                    url = location
                    conn.close()
                    tries += 1
                    continue
                data = r1.read()
                conn.close()
                if sys.version_info.major < 3:
                    return data
                else:
                    encoding = r1.headers.get_content_charset(default)
                    return data.decode(encoding)
        return None
987618
def authenticate_redirect(self, callback_uri=None, cancel_uri=None,
                              extended_permissions=None, callback=None):
        
        self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME)

        scope = self._BASE_SCOPE
        if extended_permissions:
            scope += extended_permissions

        args = {'client_id': self.settings[self._CLIENT_ID_SETTING],
                'redirect_uri': self.oauth2_redirect_uri(callback_uri),
                'scope': ','.join(scope)}

        # If cookie_secret is set, use it for GitHub's state value
        if not self.state and 'cookie_secret' in self.settings:
            sha1 = hashlib.sha1(self.settings['cookie_secret'])
            self.state = str(sha1.hexdigest())

        # If state is set, add it to args
        if self.state:
            args['state'] = self.state

        LOGGER.info('Redirect args: %r', args)

        # Redirect the user to the proper URL
        self.redirect(self._OAUTH_AUTHORIZE_URL +
                      auth.urllib_parse.urlencode(args))
        callback()