Issue request against the crate HTTP API.
775196
def _json_request(self, method, path, data):
        

        response = self._request(method, path, data=data)
        _raise_for_status(response)
        if len(response.data) > 0:
            return _json_from_response(response)
        return response.data
725753
def _request(self, url, method="GET", params=None, api_call=None):
        """"""
        method = method.lower()
        params = params or {}
        func = getattr(requests, method)
        requests_args = {}
        if method == "get" or method == "delete":
            requests_args["params"] = params
        else:
            if params.get("json"):
                requests_args["json"] = params.get("json")
            if params.get("files"):
                requests_args["files"] = params.get("files")
            if params.get("data"):
                requests_args["data"] = params.get("data")
        try:
            response = func(url, **requests_args)
        except requests.RequestException as e:
            raise SafecastPyError(str(e))
        # greater than 304 (not modified) is an error
        if response.status_code > 304:
            if response.status_code == 401:
                raise SafecastPyAuthError(response.json().get("error"))
            if response.status_code in [422]:
                raise SafecastPyError(response.json().get("errors"))
            raise SafecastPyError(response.content, error_code=response.status_code)
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            raise SafecastPyError(
                "Response was not valid JSON. \
                               Unable to decode."
            )
        return content
1345437
def _http_request(self, api, data, headers=None):
        
        if not headers:
            headers = {'Content-Type': 'application/json'}
        if not self._token_valid:
            self._token = self.get_token(self._app_name, self._username, self._password)
        response = requests.post(self._base_url + '/' + api, data=json.dumps(data),
                                 headers=headers)
        # raise an exception if the status was not 200
        logger.debug(json.dumps(data))
        logger.debug(response.text)
        response.raise_for_status()
        return response
246481
def add(name)
      response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}}))
      raise CrateLimitReachedError, response["message"] unless response["status"] != "failure"
    end
668582
function request(requestOptions, callback) {
	var debug = require('debug')('analyze-css:http'),
		fetch = require('node-fetch');

	debug('GET %s', requestOptions.url);
	debug('Options: %j', requestOptions);

	fetch(requestOptions.url, requestOptions).
	then(function(resp) {
		debug('HTTP %d %s', resp.status, resp.statusText);
		debug('Headers: %j', resp.headers._headers);

		if (!resp.ok) {
			var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
			callback(err);
		} else {
			return resp.text(); // a promise
		}
	}).
	then(function(body) {
		debug('Received %d bytes of CSS', body.length);
		callback(null, body);
	}).
	catch(function(err) {
		debug(err);
		callback(err);
	});
}
630657
def do_request(self, http_verb, url, headers, data=None):
        
        if data:
            data = json.dumps(data)
        try:
            response = requests.request(http_verb, url, headers=headers, data=data, verify=config.CACERT_PATH)
        except (requests.exceptions.Timeout, requests.exceptions.TooManyRedirects) as exception:
            self._raise_unrecoverable_error_payplug(exception)
        except requests.exceptions.RequestException as exception:
            self._raise_unrecoverable_error_client(exception)

        return response.content, response.status_code, response.headers
839399
async def request(self, method, path, json=None):
        """"""
        url = 'https://{}:{}/api/'.format(self.host, self.port)
        url += path.format(site=self.site)

        try:
            async with self.session.request(method, url, json=json) as res:
                if res.content_type != 'application/json':
                    raise ResponseError(
                        'Invalid content type: {}'.format(res.content_type))
                response = await res.json()
                _raise_on_error(response)
                return response['data']

        except client_exceptions.ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(self.host, err)
            ) from None
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)
667421
async def _request(
            self, method: str, endpoint: str, *, headers: dict = None) -> dict:
        """"""
        url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)

        if not headers:
            headers = {}
        headers.update({
            'Host': DEFAULT_HOST,
            'Origin': DEFAULT_ORIGIN,
            'Referer': DEFAULT_ORIGIN,
            'User-Agent': DEFAULT_USER_AGENT,
        })

        async with self._websession.request(
                method,
                url,
                headers=headers,
        ) as resp:
            try:
                resp.raise_for_status()
                return await resp.json(content_type=None)
            except client_exceptions.ClientError as err:
                raise RequestError(
                    'Error requesting data from {0}: {1}'.format(
                        endpoint, err)) from None
1116919
void handleService(KNXnetIPHeader h, byte[] data, int offset)
		throws KNXFormatException, IOException
	{
		final int svc = h.getServiceType();
		if (svc == KNXnetIPHeader.DEVICE_CONFIGURATION_REQ) {
			ServiceRequest req;
			try {
				req = PacketHelper.getServiceRequest(h, data, offset);
			}
			catch (final KNXFormatException e) {
				// try to get at least the connection header of the service request
				req = PacketHelper.getEmptyServiceRequest(h, data, offset);
				final byte[] junk = new byte[h.getTotalLength() - h.getStructLength() - 4];
				System.arraycopy(data, offset + 4, junk, 0, junk.length);
				logger.warn("received dev.mgmt request with unknown cEMI part "
					+ DataUnitBuilder.toHex(junk, " "), e);
			}
			final short seq = req.getSequenceNumber();
			if (req.getChannelID() == getChannelID() && seq == getSeqNoRcv()) {
				final short status = h.getVersion() == KNXNETIP_VERSION_10 ?
					ErrorCodes.NO_ERROR	: ErrorCodes.VERSION_NOT_SUPPORTED;
				final byte[] buf =
					PacketHelper.toPacket(new ServiceAck(KNXnetIPHeader.
						DEVICE_CONFIGURATION_ACK, getChannelID(), seq, status));
				final DatagramPacket p = new DatagramPacket(buf, buf.length,
					dataEP.getAddress(), dataEP.getPort());
				socket.send(p);
				incSeqNoRcv();
				if (status == ErrorCodes.VERSION_NOT_SUPPORTED) {
					close(ConnectionCloseEvent.INTERNAL, "protocol version changed",
						LogLevel.ERROR, null);
					return;
				}
				final CEMI cemi = req.getCEMI();
				// leave if we are working with an empty (broken) service request
				if (cemi == null)
					return;
				final short mc = cemi.getMessageCode();
				if (mc == CEMIDevMgmt.MC_PROPINFO_IND || mc == CEMIDevMgmt.MC_RESET_IND)
					fireFrameReceived(cemi);
				else if (mc == CEMIDevMgmt.MC_PROPREAD_CON
					|| mc == CEMIDevMgmt.MC_PROPWRITE_CON) {
					// invariant: notify listener before return from blocking send
					fireFrameReceived(cemi);
					setStateNotify(OK);
				}
			}
			else
				logger.warn("received dev.mgmt request channel-ID " + req.getChannelID()
					+ ", receive-sequence " + seq + ", expected " + getSeqNoRcv()
					+ " - ignored");
		}
		else
			logger.warn("received unknown frame (service type 0x"
				+ Integer.toHexString(svc) + ") - ignored");
	}
178754
def _request(self, method, endpoint, id=None, **kwargs):
        ""
        request = getattr(requests, method, None)
        if not callable(request):
            raise RequestError('Invalid method %s' % method)
        # Find files, separate them out to correct kwarg for requests.
        data = kwargs.get('data')
        if data:
            files = {}
            for name, value in list(data.items()):
                # Value might be a file-like object (with a read method), or it
                # might be a (filename, file-like) tuple.
                if hasattr(value, 'read') or isinstance(value, tuple):
                    files[name] = data.pop(name)
            if files:
                kwargs.setdefault('files', {}).update(files)
        path = ['api', self.version, endpoint]
        # If we received an ID, append it to the path.
        if id:
            path.append(str(id))
        # Join fragments into a URL
        path = '/'.join(path)
        if not path.endswith('/'):
            path += '/'
        while '//' in path:
            path = path.replace('//', '/')
        url = self.url + path
        # Add our user agent.
        kwargs.setdefault('headers', {}).setdefault('User-Agent',
                                                    HTTP_USER_AGENT)
        # Now try the request, if we get throttled, sleep and try again.
        trys, retrys = 0, 3
        while True:
            if trys == retrys:
                raise RequestError('Could not complete request after %s trys.'
                                   % trys)
            trys += 1
            try:
                return self._do_request(request, url, **kwargs)
            except ResponseError as e:
                if self.throttle_wait and e.status_code == 503:
                    m = THROTTLE_PATTERN.match(
                        e.response.headers.get('x-throttle', ''))
                    if m:
                        time.sleep(float(m.group(1)))
                        continue
                # Failed for a reason other than throttling.
                raise
836026
function(res, text, httpStatus) {
		processLogger.log('fatal/request', text);
		apiUtils.errorResponse(res, text, httpStatus || 404);
	}
1237167
def _raise_for_status(self, response):
        """"""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise create_api_error_from_http_exception(e)
1307762
function makeRequest(options, callback) {
    request(options, function (error, response, body){
        if (error) {
            callback(error, null);
        }
        else if (response.statusCode == 200) {
            callback( null, JSON.parse(body));
        }
        else {
            callback(new Error('HTTP Response Code: ' + response.statusCode), null);
        }
    });
}
1211368
def request(method, path, options, headers)
      headers.merge!({
        'User-Agent' => user_agent,
        'Accept' => 'application/vnd.urbanairship+json; version=3;',
      })

      response = connection.send(method) do |request|
        request.url("#{endpoint}#{path}/")

        if [:post, :put].member?(method)
          request.body = options.to_json
        else
          request.params.merge!(options)
        end

        request.headers.merge!(headers)
      end

      Utils.handle_api_error(response) unless (200..399).include?(response.status)

      Utils.parse_message(response)
    end
996168
def exec_request(endpoint, func, raise_for_status=False, **kwargs):
        
        try:
            endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint)
            headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'}
            logger.debug(headers)
            logger.debug(endpoint)
            ret = getattr(requests, func)(endpoint, headers=headers, data=kwargs)
            ret.raise_for_status()
            return ret.json()
        except requests.HTTPError as e:
            if raise_for_status:
                raise e
            logger.exception("Error encountered while performing API request to SeAT with url {}".format(endpoint))
            return {}
633063
def raise_for_status(self):
        
        if not self.ok:
            reason = self.reason or 'No response from %s' % self.url
            if not self.status_code:
                raise HttpConnectionError(reason, response=self)

            if 400 <= self.status_code < 500:
                http_error_msg = '%s Client Error - %s - %s %s' % (
                    self.status_code, reason, self.request.method, self.url)
            else:
                http_error_msg = '%s Server Error - %s - %s %s' % (
                    self.status_code, reason, self.request.method, self.url)

            raise HttpRequestException(http_error_msg, response=self)