Make HTTP(S) request.
			headers can be either dict or callable(url, method, body, mimetype or None).
			decode (response body) = None | json.
			encode (data) = None | json | form | files.
172182
def request( self, url, method='get',
			decode=None, encode=None, data=None,
			headers=None, raise_for=dict(), queue_lines=None ):
		''''''
		if self.debug_requests:
			url_debug = _dump_trunc(url)
			log.debug('HTTP request: {} {} (h: {}, enc: {}, dec: {}, data: {!r})'.format(
				method, url_debug, headers, encode, decode, _dump_trunc(data) ))

		timeout = HTTPTimeout(**self.request_io_timeouts)
		req_headers = {'User-Agent': 'txU1'}

		if data is not None:
			if encode == 'files':
				boundary = os.urandom(16).encode('hex')
				req_headers['Content-Type'] = 'multipart/form-data; boundary={}'.format(boundary)
				data = MultipartDataSender(data, boundary)
				if not callable(headers): yield data.calculate_length()
				else:
					body = io.BytesIO()
					yield data.calculate_length(body)
					headers = headers(url, method, body.getvalue(), 'multipart/form-data')
			else:
				if encode is None:
					if isinstance(data, types.StringTypes): data = io.BytesIO(data)
				elif encode == 'form':
					req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
					data = io.BytesIO(urllib.urlencode(data))
				elif encode == 'json':
					req_headers['Content-Type'] = 'application/json'
					data = io.BytesIO(json.dumps(data))
				else: raise ValueError('Unknown request encoding: {}'.format(encode))
				if callable(headers):
					data.seek(0)
					headers = headers(url, method, data.read(), req_headers.get('Content-Type'))
				data = FileBodyProducer(data)
		elif callable(headers): headers = headers(url, method, '', None)

		# Passed "headers" should be allowed to be modified by body_hash()
		for k, v in (headers or dict()).viewitems():
			req_headers[force_bytes(k)] = force_bytes(v)
		url, method = it.imap(force_bytes, [url, method.lower()])

		if decode == 'json': req_headers.setdefault('Accept', 'application/json')
		elif decode is not None:
			raise ValueError('Unknown response decoding method: {}'.format(decode))

		res_deferred = first_result( timeout,
			self.request_agent.request( method.upper(), url,
				Headers(dict((k,[v]) for k,v in req_headers.viewitems())), data ) )
		code = res_body = None
		try:
			res = yield res_deferred
			code = res.code
			if code == http.NO_CONTENT: defer.returnValue(None)
			if code not in [http.OK, http.CREATED]:
				if self.debug_requests:
					res_body = defer.Deferred()
					res.deliverBody(DataReceiver(res_body, timer=timeout, allow_loss=True))
					res_body = yield first_result(timeout, res_body)
					log.debug('HTTP error response body: {!r}'.format(res_body))
				raise ProtocolError(code, res.phrase)

			res_body = defer.Deferred()
			res.deliverBody(DataReceiver(res_body, timer=timeout))
			res_body = yield first_result(timeout, res_body)

			if self.debug_requests:
				log.debug( 'HTTP request done ({} {}): {} {} {}, body_len: {}'\
					.format(method, url_debug, code, res.phrase, res.version, len(res_body)) )
			defer.returnValue(json.loads(res_body) if decode is not None else res_body)

		except ( timeout.ActivityTimeout, TimeoutError,
				ResponseFailed, RequestNotSent, RequestTransmissionFailed ) as err:
			if isinstance(err, timeout.ActivityTimeout):
				if not res_deferred.called: res_deferred.cancel()
				if res_body and not res_body.called: res_body.cancel()
			if self.debug_requests:
				log.debug(
					'HTTP transport (underlying protocol) error ({} {}): {}'\
					.format(method, url_debug, err.message or repr(err.args)) )
			raise UnderlyingProtocolError(err)

		except ProtocolError as err:
			if self.debug_requests:
				log.debug(
					'HTTP request handling error ({} {}, code: {}): {}'\
					.format(method, url_debug, code, err.message) )
			raise raise_for.get(code, ProtocolError)(code, err.message)

		except RequestGenerationFailed as err:
			err[0][0].raiseException()

		finally: timeout.state_finished()
328227
async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],
                            data: Any, accept: str,
                            jwt: Opt[str] = None,
                            oauth_token: Opt[str] = None,
                            ) -> Tuple[bytes, Opt[str]]:
        """"""
        if oauth_token is not None and jwt is not None:
            raise ValueError("Cannot pass both oauth_token and jwt.")
        filled_url = sansio.format_url(url, url_vars)
        if jwt is not None:
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                jwt=jwt)
        elif oauth_token is not None:
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                oauth_token=oauth_token)
        else:
            # fallback to using oauth_token
            request_headers = sansio.create_headers(
                self.requester, accept=accept,
                oauth_token=self.oauth_token)
        cached = cacheable = False
        # Can't use None as a "no body" sentinel as it's a legitimate JSON type.
        if data == b"":
            body = b""
            request_headers["content-length"] = "0"
            if method == "GET" and self._cache is not None:
                cacheable = True
                try:
                    etag, last_modified, data, more = self._cache[filled_url]
                    cached = True
                except KeyError:
                    pass
                else:
                    if etag is not None:
                        request_headers["if-none-match"] = etag
                    if last_modified is not None:
                        request_headers["if-modified-since"] = last_modified
        else:
            charset = "utf-8"
            body = json.dumps(data).encode(charset)
            request_headers['content-type'] = f"application/json; charset={charset}"
            request_headers['content-length'] = str(len(body))
        if self.rate_limit is not None:
            self.rate_limit.remaining -= 1
        response = await self._request(method, filled_url, request_headers, body)
        if not (response[0] == 304 and cached):
            data, self.rate_limit, more = sansio.decipher_response(*response)
            has_cache_details = ("etag" in response[1]
                                 or "last-modified" in response[1])
            if self._cache is not None and cacheable and has_cache_details:
                etag = response[1].get("etag")
                last_modified = response[1].get("last-modified")
                self._cache[filled_url] = etag, last_modified, data, more
        return data, more
165421
def _do_request(self, method, *args, **kwargs):
        
        log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
            args[0], kwargs.get('headers'), kwargs.get('json'), method,),
            level=logging.DEBUG,)
        requests_method = getattr(requests, method)
        return self._handle_response(requests_method(*args, **kwargs))
402700
def _request(self, method, url, params=None, files=None):
        """"""
        if not params:
            params = {}
        params['apiKey'] = self.api_key

        headers = {
            'User-Agent': self.user_agent,
            'Accept': 'application/json'
        }

        try:
            if self.debug:
                print(method + ' ' + url)
                print(params)

            response = requests.request(method=method, url=self.host + url, params=params, files=files, headers=headers,
                                        timeout=self.timeout, verify=self.verify_ssl, cert=self.cert)

            if self.debug:
                print(response.status_code)
                print(response.text)

            try:
                json_response = response.json()

                message = json_response['message']
                success = json_response['success']
                response_code = json_response['responseCode']
                data = json_response['object']

                return ThreadFixResponse(message=message, success=success, response_code=response_code, data=data)
            except ValueError:
                return ThreadFixResponse(message='JSON response could not be decoded.', success=False)
        except requests.exceptions.SSLError:
            return ThreadFixResponse(message='An SSL error occurred.', success=False)
        except requests.exceptions.ConnectionError:
            return ThreadFixResponse(message='A connection error occurred.', success=False)
        except requests.exceptions.Timeout:
            return ThreadFixResponse(message='The request timed out after ' + str(self.timeout) + ' seconds.',
                                     success=False)
        except requests.exceptions.RequestException:
            return ThreadFixResponse(message='There was an error while handling the request.', success=False)
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)
827982
def get(self, url, headers=None, kwargs=None):
        
        return self._request(
            method='get',
            url=url,
            headers=headers,
            kwargs=kwargs
        )
1214415
def request(method, url, headers=None, data=None, session=None):
    
    base_headers = {
        'User-Agent': random_agent()
    }
    if headers is None:
        headers = {}

    base_headers.update(headers)

    if 'Content-Length' in headers:
        del base_headers['Content-Length']

    headers = base_headers
    if session is not None:
        req = session.request
    else:
        req = requests.request

    r = req(method, url, headers=headers, data=data)
    return r
287758
def _make_request(self, method, url, post_data=None, body=None):
        
        if not self.connection:
            self._connect()
        try:
            self.connection.close()
        except:
            pass
        self.connection.connect()
        headers = {}
        if self.auth_header:
            headers["Authorization"] = self.auth_header
        self.connection.request(method, url, body, headers)
        resp = self.connection.getresponse()
        return resp
27383
def request(self, url, method, data=None, headers=None):
        
        http_headers = merge_dict(self.default_headers, headers or {})
        request_data = merge_dict({'api_key': self.apikey}, data or {})

        logger.info('HTTP %s REQUEST TO %s' % (method, url))

        start = datetime.datetime.now()

        try:
            response = requests.request(method=method, url=url, data=json.dumps(request_data),
                                        headers=http_headers)
        except exceptions.BadRequestError as e:
            return json.loads({'errors': e.content})

        duration = datetime.datetime.now() - start

        logger.info('RESPONSE %s DURATION %s.%s' % (response.encoding, duration.seconds,
                                                    duration.microseconds))

        return json.loads(response.content) if response.content else {}
358648
def _request(self, method, body=None, raise_exc=True, headers=None, files=None):
        ''''''
        headers = headers or {}
        if body and 'Content-Type' not in headers:
            headers.update({'Content-Type': 'application/json'})
        response = self._core.session.request(
            method,
            self.uri,
            data=body if not isinstance(body, dict) else None,
            json=body if isinstance(body, dict) else None,
            files=files,
            headers=headers,
            allow_redirects=False,
        )
        nav = self._create_navigator(response, raise_exc=raise_exc)
        if raise_exc and not response:
            raise exc.HALNavigatorError(
                message=response.text,
                status=response.status_code,
                nav=nav,  # may be self
                response=response,
            )
        else:
            return nav
752605
def _request(self, method, resource_uri, **kwargs):
        
        data = kwargs.get('data')
        response = method(self.API_BASE_URL + resource_uri,
                          json=data, headers=self.headers)
        response.raise_for_status()
        return response.json()
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
998873
def make_request(method, path, options, raw=false)
      options.merge!({:key => api_key, :id => api_id })

      response = connection(raw).send(method) do |request|
        case method
        when :get, :delete
          request.url(path, options)
        when :post, :put
          request.path = path
          request.body = options unless options.empty?
        end
      end
      return response if raw
      return response.body
    end
380228
def handle(self, request, uri):
        

        # Convert the call over to Stack-In-A-Box
        method = request.method
        headers = CaseInsensitiveDict()
        request_headers = CaseInsensitiveDict()
        request_headers.update(request.headers)
        request.headers = request_headers
        stackinabox_result = StackInABox.call_into(method,
                                                   request,
                                                   uri,
                                                   headers)

        # reformat the result for easier use
        status_code, output_headers, body = stackinabox_result

        json_data = None
        text_data = None
        content_data = None
        body_data = None

        # if the body is a string-type...
        if isinstance(body, six.string_types):
            # Try to convert it to JSON
            text_data = body
            try:
                json_data = json.dumps(text_data)
                text_data = json_data
            except Exception:
                json_data = None
                text_data = body

        # if the body is binary, then it's the content
        elif isinstance(body, six.binary_type):
            content_data = body

        # by default, it's just body data
        else:
            # default to body data
            body_data = body

        # build the Python requests' Response object
        return requests_mock.response.create_response(
            request,
            headers=output_headers,
            status_code=status_code,
            body=body_data,
            json=json_data,
            text=text_data,
            content=content_data
        )
1374568
function(method, url, headers, data, callback) {

		var r = new XMLHttpRequest();
		var error = this.error;

		// Binary?
		var binary = false;
		if (method === 'blob') {
			binary = method;
			method = 'GET';
		}

		method = method.toUpperCase();

		// Xhr.responseType 'json' is not supported in any of the vendors yet.
		r.onload = function(e) {
			var json = r.response;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {
				if (r.status === 401) {
					json = error('access_denied', r.statusText);
				}
			}

			var headers = headersToJSON(r.getAllResponseHeaders());
			headers.statusCode = r.status;

			callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
		};

		r.onerror = function(e) {
			var json = r.responseText;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {}

			callback(json || error('access_denied', 'Could not get resource'));
		};

		var x;

		// Should we add the query to the URL?
		if (method === 'GET' || method === 'DELETE') {
			data = null;
		}
		else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
			// Loop through and add formData
			var f = new FormData();
			for (x in data) if (data.hasOwnProperty(x)) {
				if (data[x] instanceof HTMLInputElement) {
					if ('files' in data[x] && data[x].files.length > 0) {
						f.append(x, data[x].files[0]);
					}
				}
				else if (data[x] instanceof Blob) {
					f.append(x, data[x], data.name);
				}
				else {
					f.append(x, data[x]);
				}
			}

			data = f;
		}

		// Open the path, async
		r.open(method, url, true);

		if (binary) {
			if ('responseType' in r) {
				r.responseType = binary;
			}
			else {
				r.overrideMimeType('text/plain; charset=x-user-defined');
			}
		}

		// Set any bespoke headers
		if (headers) {
			for (x in headers) {
				r.setRequestHeader(x, headers[x]);
			}
		}

		r.send(data);

		return r;

		// Headers are returned as a string
		function headersToJSON(s) {
			var r = {};
			var reg = /([a-z\-]+):\s?(.*);?/gi;
			var m;
			while ((m = reg.exec(s))) {
				r[m[1]] = m[2];
			}

			return r;
		}
	}
481471
def _make_request(self, request):
        
        # TODO: I'm sure all kinds of error checking needs to go here
        try:
            response_raw = urllib2.urlopen(request)
        except urllib2.HTTPError, e:
            print e.read()
            raise

        response_str = response_raw.read()
        response = json.loads(response_str)

        self._last_request = request
        self._last_response = response_raw
        self._last_response_str = response_str
        return response
228330
def _http_request(url,
                  method='GET',
                  headers=None,
                  data=None):
    '''
    
    '''
    req = requests.request(method,
                           url,
                           headers=headers,
                           data=data)
    ret = _default_ret()
    ok_status = METHOD_OK_STATUS.get(method, 200)
    if req.status_code != ok_status:
        ret.update({
            'comment': req.json().get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json() if method != 'DELETE' else None  # no body when DELETE
    })
    return ret