send an http request and return a json object if no error occurred.
764993
def _http_call(the_url, method, authorization, **kw):
    '''
    
    '''
    params = None
    boundary = None
    if method == _HTTP_UPLOAD:
        # fix sina upload url:
        the_url = the_url.replace('https://api.', 'https://upload.api.')
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
        if '/remind/' in the_url:
            # fix sina remind api:
            the_url = the_url.replace('https://api.', 'https://rm.api.')
    http_url = '%s?%s' % (the_url, params) if method == _HTTP_GET else the_url
    http_body = None if method == _HTTP_GET else params
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if authorization:
        req.add_header('Authorization', 'OAuth2 %s' % authorization)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        body = _read_body(resp)
        r = _parse_json(body)
        if hasattr(r, 'error_code'):
            raise APIError(r.error_code, r.get('error', ''), r.get('request', ''))
        return r
    except urllib2.HTTPError as e:
        try:
            r = _parse_json(_read_body(e))
        except:
            r = None
        if hasattr(r, 'error_code'):
            raise APIError(r.error_code, r.get('error', ''), r.get('request', ''))
        raise e
878741
def post(self, url, data):
        
        try:
            res = requests.post(
                url, headers=self.headers, data=json.dumps(data))
            return json.loads(res.text)
        except Exception as e:
            print(e)
            return "error"
702605
def request(url, *args, **kwargs):
    """"""
    method = kwargs.get('method', 'GET')
    timeout = kwargs.pop('timeout', 10)  # hass default timeout
    req = requests.request(method, url, *args, timeout=timeout, **kwargs)
    data = req.json()
    _LOGGER.debug(json.dumps(data))
    return data
692427
def request(self, *args, **kwargs):
        """"""
        try:
            return self._http.request(*args, timeout=TIMEOUT, **kwargs)
        except Exception as exc:
            raise RequestException(exc, args, kwargs)
61344
def request(self, method, url, body=None, headers={}):
        """"""
        self._send_request(method, url, body, headers)
594491
def send_http_request_with_json(context, method):
    
    safe_add_http_request_context_to_behave_context(context)
    context.http_request_context.body_params = json.loads(context.text)
    context.http_request_context.renderer = JSONRenderer()
    send_http_request(context, method)
333789
def jsonify(self,
                data: Any,
                code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK,
                headers: Optional[Dict[str, str]] = None,
                ):
        
        return jsonify(data), code, headers or {}
1240854
def json(content, request=None, response=None, ensure_ascii=False, **kwargs):
    """"""
    if hasattr(content, 'read'):
        return content

    if isinstance(content, tuple) and getattr(content, '_fields', None):
        content = {field: getattr(content, field) for field in content._fields}
    return json_converter.dumps(content, default=_json_converter, ensure_ascii=ensure_ascii, **kwargs).encode('utf8')
1018111
def get_send_result(self):
        """"""
        send_result = self.json_response.get("send_result", None)
        self.logger.info("%s\t%s" % (self.request_method, self.request_url))
        return send_result
433277
def _post_request(self, url, data=None, json=None, **kwargs):
        
        '''  '''
        
    # construct request kwargs
        request_kwargs = {
            'method': 'POST',
            'url': url,
            'data': data,
            'json': json
        }
        for key, value in kwargs.items():
            request_kwargs[key] = value

    # send request and handle response
        return self._request(**request_kwargs)
1075160
def _request(self, method, path, params=None):
        """"""
        url = self._base_url + path

        try:
            if method == 'GET':
                response = requests.get(url, timeout=TIMEOUT)
            elif method == "POST":
                response = requests.post(url, params, timeout=TIMEOUT)
            elif method == "PUT":
                response = requests.put(url, params, timeout=TIMEOUT)
            elif method == "DELETE":
                response = requests.delete(url, timeout=TIMEOUT)

            if response:
                return response.json()
            else:
                return {'status': 'error'}
        except requests.exceptions.HTTPError:
            return {'status': 'error'}
        except requests.exceptions.Timeout:
            return {'status': 'offline'}
        except requests.exceptions.RequestException:
            return {'status': 'offline'}
1338326
def json_response(data, status=200):
    """"""
    from django.http import JsonResponse
    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))
216149
def request(self, path, method='GET', params=None, type=REST_TYPE):
        """"""
        response_text = self._get_http_client(type).request(path, method, params)

        if not response_text:
            return response_text

        response_json = json.loads(response_text)

        if 'errors' in response_json:
            raise (ErrorException([Error().load(e) for e in response_json['errors']]))

        return response_json
644174
def post(self, json=None):
        
        return self._call('post', url=self.endpoint, json=json)
671993
def _http_request(url,
                  headers=None,
                  data=None):
    '''
    
    '''
    if not headers:
        headers = _get_headers()
    session = requests.session()
    log.debug('Querying %s', url)
    req = session.post(url,
                       headers=headers,
                       data=salt.utils.json.dumps(data))
    req_body = req.json()
    ret = _default_ret()
    log.debug('Status code: %d', req.status_code)
    log.debug('Response body:')
    log.debug(req_body)
    if req.status_code != 200:
        if req.status_code == 500:
            ret['comment'] = req_body.pop('message', '')
            ret['out'] = req_body
            return ret
        ret.update({
            'comment': req_body.get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json()
    })
    return ret
825433
def _http_call(self, url, method, data=None, **kwargs):
        
        response = self._http_response(url, method, data=data, **kwargs)
        if not response.content:
            return {}

        return response.json()
1359726
function json(url, obj, headers, fn){
  if (3 == arguments.length) fn = headers, headers = {};

  var req = new XMLHttpRequest;
  req.onerror = fn;
  req.onreadystatechange = done;
  req.open('POST', url, true);
  for (var k in headers) req.setRequestHeader(k, headers[k]);
  req.send(JSON.stringify(obj));

  function done(){
    if (4 == req.readyState) return fn(null, req);
  }
}