Send http request and return response text.
332361
def _http(method, url, headers=None, **kw):
    '''
    
    '''
    params = None
    boundary = None
    if method == 'UPLOAD':
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url
    http_body = None if method == 'GET' else params
    logging.error('%s: %s' % (method, http_url))
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if headers:
        for k, v in headers.iteritems():
            req.add_header(k, v)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        return _read_http_body(resp)
    finally:
        pass
1241431
def _request(self, function, params, method='POST', headers={}):
        """"""
        
        if method is 'POST':
            params = urllib.parse.urlencode(params)
            headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" }
        
        path = '/%s/%s' % (self._version, function)
        
        self._conn.request(method, path, params, headers)
        return self._conn.getresponse()
1230005
def sendrequest(self, request):
        '''
            
        '''
        url = urlparse.urlparse(self.connection.healthserviceurl)
        conn = None
        if url.scheme == 'https':
            conn = httplib.HTTPSConnection(url.netloc)
        else:
            conn = httplib.HTTPConnection(url.netloc)
        conn.putrequest('POST', url.path)
        conn.putheader('Content-Type', 'text/xml')
        conn.putheader('Content-Length', '%d' % len(request))
        conn.endheaders()
        try:
            conn.send(request)
        except socket.error, v:
            if v[0] == 32:      # Broken pipe
                conn.close()
            raise
        response = conn.getresponse().read()
        return etree.fromstring(response)
1024853
def send_response(self, code, message=None):
        
        self.log_request(code)
        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
            else:
                message = ''
        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                             (self.protocol_version, code, message))
            # print (self.protocol_version, code, message)
        self.send_header('Server', self.version_string())
        self.send_header('Date', self.date_time_string())
833459
async def send_http_response(writer,
                             http_code: int,
                             headers: List[Tuple[str, str]],
                             content: bytes,
                             http_status: str= None
                             ) -> None:
    
    # generate response payload
    if not http_status:
        http_status = STATUS_CODES.get(http_code, 'Unknown')

    response: bytes = f'HTTP/1.1 {http_code} {http_status}\r\n'.encode()
    for k, v in headers:
        response += f'{k}: {v}\r\n'.encode()
    response += b'\r\n'
    response += content

    # send payload
    writer.write(response)
    await writer.drain()
1272004
def _urllib_send(opener, req, **kwargs):
    """"""
    if req.content and not any(h.lower() == 'content-type'
                               for h in req.headers):
        req = req.with_headers({'Content-Type': 'application/octet-stream'})
    url = req.url + '?' + urlencode(req.params)
    raw_req = urllib_request.Request(url, req.content, headers=req.headers)
    set_urllib_method(raw_req, req.method)
    try:
        res = opener.open(raw_req, **kwargs)
    except urllib_http_error_cls as http_err:
        res = http_err
    return Response(res.getcode(), content=res.read(), headers=res.headers)
415047
function respondText(res, code, text) {
  res.statusCode = code;
  res.setHeader('Content-Type', 'text/plain');
  return res.end(text.toString());
}
1176090
def response(self, url):
        """"""
        
        resp = requests.get(url).content
        return self.parseresponse(resp)
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)
752514
def _http_response(self, url, method, data=None, **kwargs):
        
        header = {'content-type': 'application/json'}

        if data:
            data = json.dumps(data)
        path = url.format(**kwargs)
        logger.debug("%s %s", method.__name__.upper(), path)
        response = method(self.host + path,
                          data=data, headers=header, **self.method_kwargs)
        logger.debug("%s %s", response.status_code, response.reason)
        response.raise_for_status()

        return response
550070
protected function sendRequest()
    {
        $context = stream_context_create($this->request);
        $response = trim(file_get_contents($this->endpoint, FALSE, $context));
        $this->response = new Response($http_response_header, $response, $this->request);

        return $this->response;
    }
692427
def request(self, *args, **kwargs):
        """"""
        try:
            return self._http.request(*args, timeout=TIMEOUT, **kwargs)
        except Exception as exc:
            raise RequestException(exc, args, kwargs)
1164585
async def request(self, method, path, json=None, auth=True):
        """"""
        url = 'http://{}/api/'.format(self.host)
        if auth:
            url += '{}/'.format(self.username)
        url += path

        try:
            async with self.websession.request(method, url, json=json) as res:
                if res.content_type != 'application/json':
                    raise ResponseError(
                        'Invalid content type: {}'.format(res.content_type))
                data = await res.json()
                _raise_on_error(data)
                return data
        except client_exceptions.ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(self.host, err)
            ) from None
61344
def request(self, method, url, body=None, headers={}):
        """"""
        self._send_request(method, url, body, headers)
1116876
async def send_request(self, params, timeout,
                           type='json_query', command=False):
        """"""
        try:
            with async_timeout.timeout(timeout):
                url = '{url}{type}'.format(
                    url=self._http_url,
                    type=type)
                async with self.websession.get(
                    url=url, params=params,
                        headers=self._headers) as response:
                    if response.status != HTTP_OK:
                        _LOGGER.warning(
                            "Error message %d from Epson.", response.status)
                        return False
                    if command == TURN_ON and self._powering_on:
                        self._powering_on = False
                    if type == 'json_query':
                        return await response.json()
                    return response
        except (aiohttp.ClientError, aiohttp.ClientConnectionError):
            _LOGGER.error("Error request")
            return False
323199
def _make_request(self, path, method='GET', params_=None):
        """"""
        uri = self.api_root + path
        if params_:
            params_['text_format'] = self.response_format
        else:
            params_ = {'text_format': self.response_format}

        # Make the request
        response = None
        try:
            response = self._session.request(method, uri,
                                            timeout=self.timeout,
                                            params=params_)
        except Timeout as e:
            print("Timeout raised and caught:\n{e}".format(e=e))

        # Enforce rate limiting
        time.sleep(max(self._SLEEP_MIN, self.sleep_time))
        return response.json()['response'] if response else None
1241669
def create_response(self, request, image, content_type):
        """"""

        return HttpResponse(content=image, content_type=content_type)