Send a request to the server and return the result
513710
def doQuery(self, url, method='GET', getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}):
        """"""

        # Build headers
        headers = {}

        if not postParameters:
            postParameters = {}

        for key, value in extraHeaders.iteritems():
            # Fixes #197 for values with utf-8 chars to be passed into plugit
            if isinstance(value, basestring):
                headers['X-Plugit-' + key] = value.encode('utf-8')
            else:
                headers['X-Plugit-' + key] = value

        for key, value in session.iteritems():
            headers['X-Plugitsession-' + key] = value
            if 'Cookie' not in headers:
                headers['Cookie'] = ''
            headers['Cookie'] += key + '=' + str(value) + '; '

        if method == 'POST':
            if not files:
                r = requests.post(self.baseURI + '/' + url, params=getParmeters, data=postParameters, stream=True, headers=headers)
            else:
                # Special way, for big files
                # Requests is not usable: https://github.com/shazow/urllib3/issues/51

                from poster.encode import multipart_encode, MultipartParam
                from poster.streaminghttp import register_openers
                import urllib2
                import urllib

                # Register the streaming http handlers with urllib2
                register_openers()

                # headers contains the necessary Content-Type and Content-Length
                # datagen is a generator object that yields the encoded parameters
                data = []
                for x in postParameters:
                    if isinstance(postParameters[x], list):
                        for elem in postParameters[x]:
                            data.append((x, elem))
                    else:
                        data.append((x, postParameters[x]))

                for f in files:
                    data.append((f, MultipartParam(f, fileobj=open(files[f].temporary_file_path(), 'rb'), filename=files[f].name)))

                datagen, headers_multi = multipart_encode(data)

                headers.update(headers_multi)

                if getParmeters:
                    get_uri = '?' + urllib.urlencode(getParmeters)
                else:
                    get_uri = ''

                # Create the Request object
                request = urllib2.Request(self.baseURI + '/' + url + get_uri, datagen, headers)

                re = urllib2.urlopen(request)

                from requests import Response

                r = Response()
                r.status_code = re.getcode()
                r.headers = dict(re.info())
                r.encoding = "application/json"
                r.raw = re.read()
                r._content = r.raw

                return r

        else:
            # Call the function based on the method.
            r = requests.request(method.upper(), self.baseURI + '/' + url, params=getParmeters, stream=True, headers=headers, allow_redirects=True)

        return r
396773
def do_request(self, line):
        

        def f(p, method, params):
            result = p.call(method, params)
            print("RESULT %s" % result)

        self._request(line, f)
479404
def request(self, method, url, *args):
        
        return self.http.request(method, url, *args)
516560
function sendResponse(success) {
        success = success || false;
        response.status(200);
        response.contentType('application/json');
        response.send(JSON.stringify({success: success}));
      }
65408
def request(self, url, method="GET", params=None, headers=None):
        
        params = params or {}
        headers = headers or {}

        logger.debug("URL: %s", url)
        logger.debug("Method: %s", method)
        logger.debug("Headers: %s", headers)
        logger.debug("Params: %s", params)
        
        response, content = self.client().request(url, method, headers=headers,
            body=urllib.urlencode(params))
        
        content = smart_unicode(content)

        logger.debug("Status: %s", response['status'])
        logger.debug("Content: %s", content)
        
        if response['status'] != '200':
            raise OAuthError(_(
                u"Invalid status code %s while requesting %s: %s") % (
                    response['status'], url, content))
        
        return content
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
1301289
function send(req, res, next){
  /**
   * [type description]
   * @param  {[type]} type    [description]
   * @param  {[type]} options [description]
   * @return {[type]}         [description]
   */
  res.type = function(type, options){
    type = CONTENT_TYPES[ type ] || type;
    options = Object.keys(options || {}).map(function(name){
      return [ name, options[ name ] ].join('=');
    }).join('; ');
    res.setHeader('Content-Type', type + (options ? ('; ' + options) : ''));
    return res;
  };
  /**
   * [header description]
   * @param  {[type]} name  [description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  res.header = function(name, value){
    res.setHeader(name, value);
    return res;
  };
  
  /**
   * [status description]
   * @param  {[type]} code [description]
   * @return {[type]}      [description]
   */
  res.status = function(code){
    this.statusCode = code;
    return res;
  };

  /**
   * [redirect description]
   * @param  {[type]} url     [description]
   * @param  {[type]} code    [description]
   * @param  {[type]} headers [description]
   * @return {[type]}         [description]
   */
  res.redirect = function(url, code){
    this.status(code || 302);
    this.header('Location', url);
    return res.end();
  };
  
  /**
   * [send description]
   * @param  {[type]} body [description]
   * @return {[type]}      [description]
   */
  res.send = body => {
    var type = ({})
      .toString
      .call(body)
      .match(/^\[object (\w+)\]$/)[1]
      .toLowerCase();

    if(type === 'object' && body.then)
      type = 'promise';
      
    if(type === 'object' && (body instanceof Stream))
      type = 'stream';
    
    if(type === 'object' && (body instanceof Buffer))
      type = 'buffer';

    if(type === 'object' && (body instanceof Response))
      type = 'response';
      
    switch(type){
      case 'number':
        res.status(body);
        res.send(STATUS_CODES[body]);
        break;
      case 'function':
        body = body(req, res);
        body && res.send(body);
        break;
      case 'error':
        res.send(body.stack);
        break;
      case 'promise':
        body.then(res.send, next);
        break;
      case 'stream':
        body.pipe(res);
        break;
      case 'array':
      case 'object':
        res.type('json');
        res.send(JSON.stringify(body));
        break;
      case 'string':
      case 'buffer':
      case 'uint8array':
        res.end(body);
        break;
      case 'response':
        body.respond(req, res);
        break;
      default:
        res.end();
        break;
    }
    return res;
  };
  return next();
}
1012175
def send_request(self, request):
        """"""
        self.log.debug('send_request: in')

        message = {'callId': self.call_id, 'req': request}
        self.log.debug('send_request: %s', Pretty(message))
        self.send(json.dumps(message))

        call_id = self.call_id
        self.call_id += 1
        return call_id
402918
def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None):
        '''
        
        '''
        if time_stamp == 0:
            time_stamp = int(time.time())

        if specific_servers == None:
            specific_servers = self.servers
        else:
            specific_servers = set(self.servers).intersection(specific_servers)

        for server in specific_servers:
            post_data = {}
            post_data['time_stamp'] = time_stamp
            post_data['host_name'] = self.servers[server]['custom_fqdn']
            post_data['service_description'] = service_description
            post_data['return_code'] = return_code
            post_data['output'] = output

            if self.servers[server]['availability']:
                url = '%s://%s:%s%s' % (self.servers[server]['protocol'],
                                         self.servers[server]['host'],
                                         self.servers[server]['port'],
                                         self.servers[server]['uri'])

                auth = (self.servers[server]['username'],
                        self.servers[server]['password'])

                try:
                    response = requests.post(url,
                                             auth=auth,
                                             headers=self.http_headers,
                                             verify=self.servers[server]['verify'],
                                             timeout=self.servers[server]['timeout'],
                                             data=post_data)
                    if response.status_code == 400:
                        LOG.error("[ws_shinken][%s]: HTTP status: %s - The content of the WebService call is incorrect",
                                      server,
                                      response.status_code)
                    elif response.status_code == 401:
                        LOG.error("[ws_shinken][%s]: HTTP status: %s - You must provide an username and password",
                                      server,
                                      response.status_code)
                    elif response.status_code == 403:
                        LOG.error("[ws_shinken][%s]: HTTP status: %s - The username or password is wrong",
                                      server,
                                      response.status_code)
                    elif response.status_code != 200:
                        LOG.error("[ws_shinken][%s]: HTTP status: %s", server, response.status_code)
                except (requests.ConnectionError, requests.Timeout), error:
                    self.servers[server]['availability'] = False
                    LOG.error(error)
            else:
                LOG.error("[ws_shinken][%s]: Data not sent, server is unavailable", server)

            if self.servers[server]['availability'] == False and self.servers[server]['cache'] == True:
                self.servers[server]['csv'].writerow(post_data)
                LOG.info("[ws_shinken][%s]: Data cached", server)
308371
def send_result(self, additional_dict):
        '''
        
        '''
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        response = {
            'jsonrpc': self.req_rpc_version,
            'id': self.req_id,
        }
        response.update(additional_dict)
        jresponse = json.dumps(response)
        self.send_header("Content-length", len(jresponse))
        self.end_headers()
        self.wfile.write(jresponse.encode())
949365
def _request(self, method, url, params=None, headers=None, data=None):
        """"""
        if not params:
            params = {}

        # set default headers
        if not headers:
            headers = {
                'accept': '*/*'
            }
            if method == 'POST' or method == 'PUT':
                headers.update({'Content-Type': 'application/json'})
        try:
            response = requests.request(method=method, url=self.host + self.key + url, params=params,
                                        headers=headers, data=data)

            try:
                response.raise_for_status()

                response_code = response.status_code
                success = True if response_code // 100 == 2 else False
                if response.text:
                    try:
                        data = response.json()
                    except ValueError:
                        data = response.content
                else:
                    data = ''

                response_headers = response.headers

                return BurpResponse(success=success, response_code=response_code, data=data,
                                    response_headers=response_headers)
            except ValueError as e:
                return BurpResponse(success=False, message="JSON response could not be decoded {}.".format(e))
            except requests.exceptions.HTTPError as e:
                if response.status_code == 400:
                    return BurpResponse(success=False, response_code=400, message='Bad Request')
                else:
                    return BurpResponse(
                        message='There was an error while handling the request. {}'.format(response.content),
                        success=False)
        except Exception as e:
            return BurpResponse(success=False, message='Eerror is %s' % e)
185475
def request(self, method, path, **options):
        """"""
        options = self._merge_options(options)
        url = options['base_url'] + path
        retry_count = 0
        request_options = self._parse_request_options(options)
        self._add_version_header(request_options)
        while True:
            try:
                response = getattr(self.session, method)(
                    url, auth=self.auth, **request_options)
                if response.status_code in STATUS_MAP:
                    raise STATUS_MAP[response.status_code](response)
                elif 500 <= response.status_code < 600:
                    # Any unhandled 500 is a server error.
                    raise error.ServerError(response)
                else:
                    if options['full_payload']:
                        return response.json()
                    else:
                        return response.json()['data']
            except error.RetryableAsanaError as e:
                if retry_count < options['max_retries']:
                    self._handle_retryable_error(e, retry_count)
                    retry_count += 1
                else:
                    raise e
573029
def execute(self):
        
        url = os.path.join(self.HTTP_ENDPOINT, self.format)
        self.response = ExportResponse.load_http_response(
            self.session.post(url, data=self.json_payload)
        )
        return self.response.result
1151746
def send(self, request):
        ''''''
        return self.session.send(request(self.url, self.auth))
61464
function request() {
                return ajax.request(url, {
                    success: function () {
                        var retryAfter,
                            req;

                        if (!aborted) {
                            req = this.rawRequest;
                            // check status code for 202
                            if (this.status === 202 && util.isFn(req.getResponseHeader)) {
                                // retry the request
                                retryAfter = parseInt(req.getResponseHeader('retry-after'));
                                if (retryAfter > 0) {
                                    setTimeout(request, retryAfter * 1000);
                                    return;
                                }
                            }
                            if (this.responseText) {
                                $deferred.resolve(this.responseText);
                            } else {
                                // the response was empty, so consider this a
                                // failed request
                                retryOrFail({
                                    error: 'empty response',
                                    status: this.status,
                                    resource: url
                                });
                            }
                        }
                    },
                    fail: function () {
                        if (!aborted) {
                            retryOrFail({
                                error: this.statusText,
                                status: this.status,
                                resource: url
                            });
                        }
                    }
                });
            }
61344
def request(self, method, url, body=None, headers={}):
        """"""
        self._send_request(method, url, body, headers)
1304595
def execute(self, request):
        """"""
        url = request.uri
        if request.parameters:
            url += '?' + urlencode(request.parameters)

        if request.headers:
            headers = dict(self._headers, **request.headers)
        else:
            headers = self._headers

        
        retry = 0
        server = getattr(self._local, "server", None)
        while True:
            if not server:
                self._local.server = server = self._get_server()
            try:
                parse_result = urlparse(server)
                conn = get_pool().connection_from_host(parse_result.hostname,
                                                         parse_result.port,
                                                         parse_result.scheme)
                kwargs = dict(
                    method=Method._VALUES_TO_NAMES[request.method],
                    url=parse_result.path + url,
                    body=request.body,
                    headers=headers,
                    timeout=self._timeout,
                )

                response = conn.urlopen(**kwargs)
                return RestResponse(status=response.status,
                                    body=response.data,
                                    headers=response.headers)
            except (IOError, urllib3.exceptions.HTTPError) as ex:
                self._drop_server(server)
                self._local.server = server = None
                if retry >= self._max_retries:
                    logger.error("Client error: bailing out after %d failed retries",
                                 self._max_retries, exc_info=1)
                    raise NoServerAvailable(ex)
                logger.exception("Client error: %d retries left", self._max_retries - retry)
                retry += 1