Sends request to facebook graph
	Returns the facebook-json response converted to python object
771668
def send_request(req_cat, con, req_str, kwargs):
	
        try:
                kwargs = parse.urlencode(kwargs)    #python3x
        except:
                kwargs = urllib.urlencode(kwargs)   #python2x
        
        """
        Wrapper to keep TCP connection ESTABLISHED. Rather the connection go to
        CLOSE_WAIT and raise errors CannotSendRequest or the server reply with
        empty and it raise BadStatusLine
        """        
        try:
            con.request(req_cat, req_str, kwargs)      #send request to facebook graph
        except httplib.CannotSendRequest:
            con = create()
            con.request(req_cat, req_str, kwargs)

        try:
            res = con.getresponse().read()		   #read response
        except (IOError, httplib.BadStatusLine):
            con = create()
            con.request(req_cat, req_str, kwargs) 
            res = con.getresponse().read()  

        t = type(res)
        if type(res) == t:
                res = bytes.decode(res)
        return json.loads(res)
450666
function reqToJSON () {
  const {ip, method, url, headers} = this
  const userAgent = headers ? headers['user-agent'] : void (0)
  return {ip, method, url, userAgent}
}
1274402
def _send(self, params):
        
        # Get a response
        try:
            r = requests.get(self.url, params=params)
        # catch errors, print then exit.
        except requests.exceptions.RequestException as e:
            print(e)
        return r.json(strict=False)
1322088
def json_request_response(f):
    
    @wraps(f)
    def wrapper(*args, **kwargs):
        response = f(*args, **kwargs)
        response.raise_for_status()
        return json.loads(response.content.decode('utf-8'))

    API_FUNCTIONS[f.__name__] = f
    return wrapper
225443
def jsonp_response(data, callback="f", status=200, serializer=None):
    
    val = json.dumps(data, default=serializer)
    ret = "{callback}('{val}');".format(callback=callback, val=val)

    return HttpResponse(ret,
                        status=status,
                        content_type='application/x-javascript; charset=UTF-8')
199004
def json(
    body,
    status=200,
    headers=None,
    content_type="application/json",
    dumps=json_dumps,
    **kwargs
):
    
    return HTTPResponse(
        dumps(body, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    )
974819
def _request(self, func, url, version=1, *args, **kwargs):
        
        return_json = kwargs.pop('return_json', False)
        url = self.api_url[version] + url
        response = func(url, *args, **kwargs)

        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        response.raise_for_status()

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('error')
            if error:
                raise BitstampError(error)
            elif json_response.get('status') == "error":
                raise BitstampError(json_response.get('reason'))

        if return_json:
            if json_response is None:
                raise BitstampError(
                    "Could not decode json for: " + response.text)
            return json_response

        return response
840999
public static function collectResponse(){
        self::init();
        $fb = self::$fbInstance;
        $helper = $fb->getRedirectLoginHelper();

        try {
            $accessToken = $helper->getAccessToken();
        } catch(FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch(FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        if (isset($accessToken)) {
            $oAuth2Client = $fb->getOAuth2Client();
            $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            Cookie::setItem("fb_token",$longLivedAccessToken);
            self::redirectToRedirectURL();
        }

    }
858069
def process_request(self, request):
        """"""

        # User has already been authed by alternate middleware
        if hasattr(request, "facebook") and request.facebook:
            return

        request.facebook = False

        if not self.is_valid_path(request):
            return

        if self.is_access_denied(request):
            return authorization_denied_view(request)

        request.facebook = Facebook()
        oauth_token = False

        # Is there a token cookie already present?
        if 'oauth_token' in request.COOKIES:
            try:
                # Check if the current token is already in DB
                oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token'])
            except OAuthToken.DoesNotExist:
                request.facebook = False
                return

        # Is there a code in the GET request?
        elif 'code' in request.GET:
            try:
                graph = GraphAPI()

                # Exchange code for an access_token
                response = graph.get('oauth/access_token',
                    client_id = FACEBOOK_APPLICATION_ID,
                    redirect_uri = get_post_authorization_redirect_url(request, canvas=False),
                    client_secret = FACEBOOK_APPLICATION_SECRET_KEY,
                    code = request.GET['code'],
                )
        
                components = parse_qs(response)
                
                # Save new OAuth-token in DB
                oauth_token, new_oauth_token = OAuthToken.objects.get_or_create(
                    token = components['access_token'][0],
                    issued_at = now(),
                    expires_at = now() + timedelta(seconds = int(components['expires'][0]))
                )

            except GraphAPI.OAuthError:
                pass
        
        # There isn't a valid access_token
        if not oauth_token or oauth_token.expired:
            request.facebook = False
            return
        
        # Is there a user already connected to the current token?
        try:
            user = oauth_token.user
            if not user.authorized:
                request.facebook = False
                return
            user.last_seen_at = now()
            user.save()
        except User.DoesNotExist:
            graph = GraphAPI(oauth_token.token)
            profile = graph.get('me')
            
            # Either the user already exists and its just a new token, or user and token both are new
            try:
                user = User.objects.get(facebook_id = profile.get('id'))
                if not user.authorized:
                    if new_oauth_token:
                        user.last_seen_at = now()
                        user.authorized = True
                    else:
                        request.facebook = False
                        return
            except User.DoesNotExist:
                # Create a new user to go with token
                user = User.objects.create(
                    facebook_id = profile.get('id'),
                    oauth_token = oauth_token
                )                    
            
            user.synchronize(profile)
            
            # Delete old access token if there is any and  only if the new one is different
            old_oauth_token = None
            if user.oauth_token != oauth_token:
                old_oauth_token = user.oauth_token
                user.oauth_token = oauth_token
            
            user.save()

            if old_oauth_token:
                old_oauth_token.delete()

        if not user.oauth_token.extended:
            # Attempt to extend the OAuth token, but ignore exceptions raised by
            # bug #102727766518358 in the Facebook Platform.
            #
            # http://developers.facebook.com/bugs/102727766518358/
            try:
                user.oauth_token.extend()
            except:
                pass

        request.facebook.user = user
        request.facebook.oauth_token = oauth_token
1125503
def response
      @response ||= Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
        curl_request = as_curl
        print "#{curl_request}\n" if Fb.configuration.developing?
        http.request http_request
      end
    end
225005
def post_json(self, url, data, cls=None, **kwargs):
        
        kwargs['data'] = to_json(data, cls=cls)
        kwargs['headers'] = self.default_headers
        return self.post(url, **kwargs).json()
311336
def serialize(self):
        '''
        
        '''
        return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
1317502
function _getUser(response) {

    if(response.status == 'connected') {

      // Return a Promise for the response with user details.
      return new Promise(function (resolve) {

        // Until here, `response` was FB's auth response. Here
        // we start to build bigger response by appending the Facebook's
        // user info in the `user` property.
        FB.api('/me', {
          fields: [
            'id',
            'first_name',
            'last_name' ,
            'gender',
            'link',
            'picture',
            'locale',
            'name',
            'timezone',
            'updated_time',
            'verified'
          ].toString()
        }, function (userInfo) {
          resolve(Utils.extend(response, { user: userInfo }));
        });

      });

    }else{

      // Return an already resolved promise.
      return new Promise(function (resolve) {
        resolve(response);
      });

    }

  }
1155560
def facebook_stream_fetch
      return unless facebook_status == ConnectionStatus::NORMAL
      streams = @graph.get_connections("me", "home")
      streams.each { |post| stream_print_queue << graph2item(post) }
      log(:info, "fetch stream ok")
    rescue Koala::Facebook::ServerError
      retry_wait
    rescue Koala::Facebook::APIError
      expired_session
    rescue Exception => e
      error e
    end
759299
protected function _graph($path, $method='GET', $params=array()) {
    if (is_array($method) && empty($params)) {
      $params = $method;
      $method = 'GET';
    }
    $params['method'] = $method; // method override as we always do a POST

    $result = json_decode($this->_oauthRequest(
      $this->getUrl('graph', $path),
      $params
    ), true);

    // results are returned, errors are thrown
    if (is_array($result) && isset($result['error'])) {
      $e = new FacebookApiException($result);
      if ($e->getType() === 'OAuthException') {
        $this->setSession(null);
      }
      throw $e;
    }
    return $result;
  }
893303
@Override
	public GraphRequest<JsonNode> graph(String object, Param... params) {
		return this.graph(object, JsonNode.class, params);
	}
976101
def to_json(self):
        

        result = super(Webhook, self).to_json()
        result.update({
            'name': self.name,
            'url': self.url,
            'topics': self.topics,
            'httpBasicUsername': self.http_basic_username,
            'headers': self.headers
        })

        if self.filters:
            result.update({'filters': self.filters})

        if self.transformation:
            result.update({'transformation': self.transformation})

        return result