make request

Here are the examples of how to make request in python. These are taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

196 Examples 7

    def _make_request(self, url):
        req = webob.Request.blank(url)
        req.headers['Accept'] = self.content_type
        res = req.get_response(fakes.wsgi_app(
            fake_auth_context=self.user_ctxt))
        return res

    def _make_request(self, request):
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 
                   'host': self.db}
        request.set_parameter('Version', self.service_version)
        request.sign_request(self.signature_method(), self.aws_key, self.aws_secret)
        response, content = self.http.request(request.url, request.method, headers=headers, body=request.to_postdata())
        e = ET.fromstring(content)

        error = e.find('Errors/Error')
        if error:
            raise SimpleDBError(error.find('Message').text)

        meta = e.find('{%s}ResponseMetadata' % self.ns)
        request_id = meta.find('{%s}RequestId' % self.ns).text
        usage = meta.find('{%s}BoxUsage' % self.ns).text

        return Response(response, content, request_id, usage)

    @staticmethod
    def _make_request(call, *args, **kwargs):
        """
        Handles remote service errors.
        """
        try:
            result = call(*args, **kwargs)
        except exc.GeocoderQuotaExceeded:
            raise unittest.SkipTest("Quota exceeded")
        except exc.GeocoderTimedOut:
            raise unittest.SkipTest("Service timed out")
        except exc.GeocoderUnavailable:
            raise unittest.SkipTest("Service unavailable")
        return result

    def _make_request(self, method, relative_url, signature, params=None, data=None):
        params = params or {}
        data = data or {}
        serialized = None
        default_params = self.get_default_params()
        default_params.update(params)
        headers = self.get_default_header()
        headers['Authorization'] = signature
        headers['stream-auth-type'] = 'jwt'
        url = self.get_full_url(relative_url)
        if method.__name__ in ['post', 'put']:
            serialized = serializer.dumps(data)
        response = method(url, data=serialized, headers=headers,
                          params=default_params, timeout=self.timeout)
        logger.debug('stream api call %s, headers %s data %s',
                     response.url, headers, data)
        return self._parse_response(response)

def _make_request(authenticated=False, **environ):
    """
    Make a Django request from the items in the WSGI ``environ``.
    
    """
    class MockDjangoUser(object):
        def __init__(self, authenticated):
            self.username = "foobar"
            self.authenticated = authenticated
        def is_authenticated(self):
            return self.authenticated
    request = DjangoWSGIRequest(environ)
    request.user = MockDjangoUser(authenticated)
    return request

    def _make_request(self, to_request):
        log.debug('Requesting blobs: %s', to_request)
        r_dict = {'requested_blobs': to_request}
        response_identifier = 'available_blobs'
        request = ClientRequest(r_dict, response_identifier)
        return request

    def _make_request(self, blob_details):
        blob = blob_details.blob
        request = ClientBlobRequest(
            {'requested_blob': blob.blob_hash},
            'incoming_blob',
            blob_details.counting_write_func,
            blob_details.deferred,
            blob_details.cancel_func,
            blob
        )
        log.info("Requesting blob %s from %s", blob.blob_hash, self.peer)
        return request

3
File: layer1.py, Project: boto, View license
uses: boto.log.debug
    def _make_request(self, action, verb, path, params):
        params['ContentType'] = 'JSON'
        response = self.make_request(action=action, verb='POST',
                                     path='/', params=params)
        body = response.read().decode('utf-8')
        boto.log.debug(body)
        if response.status == 200:
            return json.loads(body)
        else:
            json_body = json.loads(body)
            fault_name = json_body.get('Error', {}).get('Code', None)
            exception_class = self._faults.get(fault_name, self.ResponseError)
            raise exception_class(response.status, response.reason,
                                  body=json_body)

  def _make_request(self, url, data=None, stream=False, timeout=None):
    if data is not None:
      data = json.dumps(data)
      func = requests.post
    else:
      func = requests.get
    response = func(url,
                    data=data,
                    stream=stream,
                    timeout=timeout)
    if response.status_code != requests.codes.ok:
      raise KronosClientError('Bad status code: %d.' % response.status_code)
    if not stream:
      response = response.json()
      if not response[SUCCESS_FIELD]:
        raise KronosClientError('Encountered errors: %s' %
                                _get_errors(response))
    return response

def _make_request(path):
    req = WSGIRequest({
        'REQUEST_METHOD': 'GET',
        'PATH_INFO': path,
        'wsgi.input': StringIO()})
    req.user = AnonymousUser()
    return req

    def _make_request(self, type, path, **kwargs):
        VERBS = ['GET', 'POST', 'DELETE', 'PUT']
        if type not in VERBS:
            raise Exception('invalid request method')
        # TODO don't assume this doesn't exist in kwargs
        kwargs['headers'] = {
            'User-Agent': 'nsone-python %s python 0x%s %s'
                          % (version, sys.hexversion, sys.platform),
            'X-NSONE-Key': self._config.getAPIKey()
        }
        if 'body' in kwargs:
            kwargs['data'] = json.dumps(kwargs['body'])
            del kwargs['body']
        return self._transport.send(type, self._make_url(path), **kwargs)

    def _make_request(self, verb, url, params={}):
        request_kwargs = {
            'headers': {
                'User-Agent': self.config['user_agent'],
            },
            'timeout': self.config.get('timeout', 30),
        }
        if 'username' in self.config:
            request_kwargs['auth'] = (self.config.get('username', ''),
                                      self.config.get('password', ''))
        if verb == 'GET':
            request_kwargs['params'] = params
        else:
            request_kwargs['data'] = params
        logger.debug('%s %s' % (verb, url))
        r = requests.request(verb, url, **request_kwargs)
        self.raise_for_status(r)
        return r.json()

    def _make_request(self, method, url, params=None, **kwargs):
        expects = kwargs.pop('expects', None)
        throws = kwargs.pop('throws', None)

        kwargs['headers'] = self._build_headers(**kwargs.get('headers', {}))

        response = requests.request(method, url, params=params, auth=self._auth, **kwargs)
        if expects and response.status_code not in expects:
            raise throws if throws else HTTPError(response.status_code, message=response.content)

        return response

    def _make_request(self):
        request = testing.DummyRequest()
        request.context = testing.DummyResource()
        request.params = MultiDict()

        def flash(msg, *args, **kwargs):
            queue = kwargs.get('queue', '')
            allow_duplicate = kwargs.get('allow_duplicate', True)
            storage = request.session.setdefault('_f_' + queue, [])
            if allow_duplicate or (msg not in storage):
                storage.append(msg)
        request.session.flash = flash

        return request

    def _make_request(self):
        try:
            r = googlefinance.getQuotes('CURRENCY:USDBTC')[0]
            return defer.succeed(r)
        except Exception as err:
            return defer.fail(err)

    def _make_request(self, command):
        """
        Makes the request to the Redis Server
        :param command: Raw Redis command
        :return: Response from Redis Server
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((self.address, int(self.port)))
            s.send(command)
            response = self._recv_data(s)
            return response
        except Exception as e:
            raise BackendException(
                'Unable to make request to Redis: %s' % str(e))
        finally:
            s.close()

3
File: connection.py, Project: boto, View license
uses: boto.log.debug
    def _make_request(self, action, params, path='/', verb='GET'):
        params['ContentType'] = 'JSON'
        response = self.make_request(action=action, verb=verb,
                                     path=path, params=params)
        body = response.read().decode('utf-8')
        boto.log.debug(body)
        if response.status == 200:
            return json.loads(body)
        else:
            boto.log.error('%s %s' % (response.status, response.reason))
            boto.log.error('%s' % body)
            raise self.ResponseError(response.status, response.reason, body)

    def _make_request(self, url, data=None):
        """
            Makes a simple request. If not data is a GET else is a POST.
        """
        if not data:
            data = None
        return urllib.urlopen(url, data).read()

    def _make_request(self, path, req_params):
        uri = "{0}/{1}".format(self.endpoint, path)
        r = requests.get(uri, params=req_params,
                         auth=S3Auth(self.access_key, self.secret,
                                     self.hostname)
                         )

        if r.status_code != 200:
            raise RGWAdminAPIFailed(
                _('RGW AdminOps API returned %(status)s %(reason)s') %
                {'status': r.status_code, 'reason': r.reason})

        return r.json()

    def _make_request(self, path, url_params={}):
        url = 'https://{0}{1}?'.format(
            API_HOST,
            six.moves.urllib.parse.quote(path.encode('utf-8'))
        )
        signed_url = self.authenticator.sign_request(url, url_params)
        return self._make_connection(signed_url)

    def _make_request(self):
        from . import DummyRedis
        request = testing.DummyRequest()
        request.registry._redis_sessions = DummyRedis()
        request.exception = None
        return request

    def _make_request(self, action, params=None):
        """Make a call to the SES API.

        :type action: string
        :param action: The API method to use (e.g. SendRawEmail)

        :type params: dict
        :param params: Parameters that will be sent as POST data with the API
            call.
        """
        ct = 'application/x-www-form-urlencoded; charset=UTF-8'
        headers = {'Content-Type': ct}
        params = params or {}
        params['Action'] = action

        for k, v in params.items():
            if isinstance(v, unicode):  # UTF-8 encode only if it's Unicode
                params[k] = v.encode('utf-8')

        response = super(SESConnection, self).make_request(
            'POST',
            '/',
            headers=headers,
            data=urllib.urlencode(params)
        )
        body = response.read()
        if response.status == 200:
            list_markers = ('VerifiedEmailAddresses', 'SendDataPoints')
            e = boto.jsonresponse.Element(list_marker=list_markers)
            h = boto.jsonresponse.XmlHandler(e, None)
            h.parse(body)
            return e
        else:
            # HTTP codes other than 200 are considered errors. Go through
            # some error handling to determine which exception gets raised,
            self._handle_error(response, body)

0
File: syncapi.py, Project: bluepass, View license
uses: gruvi.Error
    def _make_request(self, method, url, headers=None, body=None):
        """Make an HTTP request to the API.
        
        This returns the HTTPResponse object on success, or None on failure.
        """
        headers = [] if headers is None else headers[:]
        agent = '{0}/{1}'.format(version_info['name'].title(), version_info['version'])
        headers.append(('User-Agent', agent))
        headers.append(('Accept', 'text/json'))
        if body is None:
            body = b''
        else:
            body = json.dumps(body).encode('utf8')
            headers.append(('Content-Type', 'text/json'))
        assert self.client is not None
        try:
            self._log.debug('client request: {} {}', method, url)
            self.client.request(method, url, headers, body)
            response = self.client.get_response()
            body = response.read()
        except gruvi.Error as e:
            self._log.error('error when making HTTP request: {}', str(e))
            return
        ctype = response.get_header('Content-Type')
        if ctype == 'text/json':
            parsed = json.try_loads(body.decode('utf8'))
            if parsed is None:
                self._log.error('response body contains invalid JSON')
                return
            response.entity = parsed
            self._log.debug('parsed "{}" request body ({} bytes)', ctype, len(body))
        else:
            response.entity = None
        return response

    def _make_request(self, register_type, host, nameservers=None, auto_resolve=True):
        """
        Make a request using dnslib, and return a DNS register.

        :param: register_type: Type of query: A, AAAA, CNAME...
        :type register_type: str

        :param host: Target host for the request.
        :type host: str

        :param nameservers: Custom name servers.
        :type nameservers: list(str)

        :param auto_resolve: configure this function to transform de dnslib register to the golismero register.
        :type auto_resolve: bool

        :return: a list with the DnsRegisters. Returned list can be empty, if a error has occurred.
        :type: list(DnsRegister)
        """
        if not isinstance(register_type, basestring):
            raise TypeError("Expected str, got '%s'" % type(type))
        if not isinstance(host, basestring):
            raise TypeError("Expected basestring, got '%s'" % type(host))
        if nameservers:
            if isinstance(nameservers, list):
                for n in nameservers:
                    if not isinstance(n, basestring):
                        raise TypeError("Expected basestring, got '%s'" % type(n))
            else:
                raise TypeError("Expected list, got '%s'" % type(nameservers))

        m_query_obj = None

        if nameservers:
            m_query_obj             = dns.resolver.Resolver(configure=False)
            m_query_obj.nameservers = nameservers
        else:
            m_query_obj             = dns.resolver.Resolver(configure=True)

            # Append the free public DNS servers for avoid errors when the DNS servers
            # configured in /etc/resolv.conf fails.
            m_query_obj.nameservers.extend(self.PUBLIC_NAMESERVERS)

        # Set timeouts
        m_query_obj.timeout         = self.REQUEST_TIMEOUT
        m_query_obj.lifetime        = self.REQUEST_TIMEOUT

        try:
            answer = m_query_obj.query(host, register_type)
        except Exception:
            return []

        if auto_resolve:
            return self._dnslib2register(register_type, answer)
        else:
            return answer

    def _make_request(self, action, params=None):
        """Make a call to the SES API.

        :type action: string
        :param action: The API method to use (e.g. SendRawEmail)

        :type params: dict
        :param params: Parameters that will be sent as POST data with the API
                       call.
        """
        ct = 'application/x-www-form-urlencoded; charset=UTF-8'
        headers = {'Content-Type': ct}
        params = params or {}
        params['Action'] = action

        for k, v in params.items():
            if isinstance(v, unicode):  # UTF-8 encode only if it's Unicode
                params[k] = v.encode('utf-8')

        response = super(SESConnection, self).make_request(
            'POST',
            '/',
            headers=headers,
            data=urllib.urlencode(params)
        )
        body = response.read()
        if response.status == 200:
            list_markers = ('VerifiedEmailAddresses', 'SendDataPoints')
            e = boto.jsonresponse.Element(list_marker=list_markers)
            h = boto.jsonresponse.XmlHandler(e, None)
            h.parse(body)
            return e
        else:
            boto.log.error('%s %s' % (response.status, response.reason))
            boto.log.error('%s' % body)
            raise self.ResponseError(response.status, response.reason, body)

    @defer.inlineCallbacks
    def _make_request(self, handle, data):
        # make sure job arg is valid json
        try:
            job_data = json.loads(data, encoding='UTF-8')
        except ValueError, e:
            defer.returnValue({"error": "Job data is not valid JSON"})

        # make sure it contains a method
        if 'method' not in job_data:
            defer.returnValue({"error":
                               "Missing \"method\" property in job data"})

        # make sure it contains data
        if 'data' not in job_data:
            defer.returnValue({"error":
                               "Missing \"data\" property in job data"})

        headers = self.build_headers(job_data)

        # we'll post the data as JSON, so convert it back
        data = json.dumps(job_data['data'])

        # select random base URL to hit
        path = random.choice(self.base_urls)
        url = str("%s/%s" % (path, job_data['method']))

        try:
            log.verbose('POSTing to %s, data=%r' % (url, data))
            postdata = urllib.urlencode({
                "job_handle": handle,
                "data": data})

            try:
                # despite our name, we're not actually using curl :)
                response = yield getPage(url, method='POST', postdata=postdata,
                                         headers=headers)
                status = 200
            except Error, e:
                status = int(e.status)
                response = e.response
            log.verbose('POST complete: status=%d, response=%r'
                             % (status, response))
            defer.returnValue({'url': url,
                               'status': status,
                               'response': response})
        except Exception, e:
            defer.returnValue({"error": "POST failed: %r - %s" % (e, e)})

    def __makerequest(self, resource_path, raw_params={}, force_get=False):
        params = urllib.urlencode(raw_params)
        
        if not resource_path in ["oauth/request_token", "oauth/access_token"]:
            resource_path = "%s.json" % (resource_path)

        if self.auth_type == "basic":
            if len(raw_params) > 0:
                if force_get:
                    request = urllib2.Request("%s/%s?%s" % (self.api_path, resource_path, params))
                else:
                    request = urllib2.Request("%s/%s" % (self.api_path, resource_path), params)
            else:
                request = urllib2.Request("%s/%s" % (self.api_path, resource_path))

            if self.auth_string is not None:
                request.add_header("Authorization", "Basic %s" % (self.auth_string))

        elif self.auth_type == "oauth":
            resource_url = "%s/%s" % (self.api_path, resource_path)

            if len(raw_params) > 0 and not force_get:
                oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token, http_method="POST", http_url=resource_url, parameters=raw_params)
            else:
                oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token, http_method="GET", http_url=resource_url, parameters=raw_params)
            oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, self.token)

            if len(raw_params) > 0 and not force_get:
                request = urllib2.Request(resource_url, data=oauth_request.to_postdata(), headers=oauth_request.to_header())
            else:
                request = urllib2.Request(oauth_request.to_url(), headers=oauth_request.to_header())

        success = False
        response = None
        attempt_count = 0
        while not success:
            success = True  # succeed unless we hit BadStatusLine
            if attempt_count >= 10:  # after 10 failed attempts
                raise Exception("Could not successfully read any response. Please check that your connection is working.")
            try:
                response = self.opener.open(request)
            except urllib2.HTTPError, e:
                raw_details = e.read()
                try:
                    err_details = json.loads(raw_details)['error']
                except ValueError:  # not JSON, use raw
                    err_details = raw_details
                if (e.code % 400) < 100:  # only throw the error further up if it's not a server error
                    raise StatusNetError(e.code, err_details)
            except urllib2.URLError, e:
                raise StatusNetError(-1, e.reason)
            except httplib.BadStatusLine, e:
                success = False
            attempt_count += 1

        if response is None:
            raise StatusNetError(-1, "Could not successfully read any response. Please check that your connection is working.")

        content = response.read()
    
        try:
            return json.loads(content)
        except ValueError:  # it wasn't JSON data, return it raw
            return content

    def _make_request(self, environ=None, postdata=None, **kw):
        environ = environ or {}
        setup_testing_defaults(environ)

        if postdata is not None:
            environ['REQUEST_METHOD'] = 'POST'
            if PY3:
                postdata = bytes(postdata, 'UTF-8')  # pragma: nocover
            environ['CONTENT_LENGTH'] = str(len(postdata))
            environ['wsgi.input'].write(postdata)
            environ['wsgi.input'].seek(0)

        def start_response(status, response_headers, exc_info=None):
            self._resp['status'] = status

        SplitMiddleware(self.app, lambda environ: 'ryan', FakeBackend(), **kw)(
            environ,
            start_response
        )
        return environ

    def _make_request(self, action, params=None):
        """Make a call to the SES API.

        :type action: string
        :param action: The API method to use (e.g. SendRawEmail)

        :type params: dict
        :param params: Parameters that will be sent as POST data with the API
                       call.
        """
        ct = 'application/x-www-form-urlencoded; charset=UTF-8'
        headers = {'Content-Type': ct}
        params = params or {}
        params['Action'] = action

        for k, v in params.items():
            if isinstance(v, basestring):
                params[k] = v.encode('utf-8')

        response = super(SESConnection, self).make_request(
            'POST',
            '/',
            headers=headers,
            data=urllib.urlencode(params)
        )
        body = response.read()
        if response.status == 200:
            list_markers = ('VerifiedEmailAddresses', 'SendDataPoints')
            e = boto.jsonresponse.Element(list_marker=list_markers)
            h = boto.jsonresponse.XmlHandler(e, None)
            h.parse(body)
            return e
        else:
            boto.log.error('%s %s' % (response.status, response.reason))
            boto.log.error('%s' % body)
            raise self.ResponseError(response.status, response.reason, body)

    def _make_request(self, method, bucket='', key='', query_args={}, headers={}, data='', metadata={}):
        server = ''
        if bucket == '':
            server = self.server
        elif self.calling_format == CallingFormat.SUBDOMAIN:
            server = "%s.%s" % (bucket, self.server)
        elif self.calling_format == CallingFormat.VANITY:
            server = bucket
        else:
            server = self.server

        path = ''

        if (bucket != '') and (self.calling_format == CallingFormat.PATH):
            path += "/%s" % bucket

        # add the slash after the bucket regardless
        # the key will be appended if it is non-empty
        path += "/%s" % urlquote(key, '/')


        # build the path_argument string
        # add the ? in all cases since 
        # signature and credentials follow path args
        if len(query_args):
            path += "?" + query_args_hash_to_string(query_args)

        is_secure = self.is_secure
        host = "%s:%d" % (server, self.port)
        while True:
            if (is_secure):
                connection = httplib.HTTPSConnection(host)
            else:
                connection = httplib.HTTPConnection(host)

            final_headers = merge_meta(headers, metadata);
            # add auth header
            self._add_aws_auth_header(final_headers, method, bucket, key, query_args)

            connection.request(method, path, data, final_headers)
            resp = connection.getresponse()
            if resp.status < 300 or resp.status >= 400:
                return resp
            # handle redirect
            location = resp.getheader('location')
            if not location:
                return resp
            # (close connection)
            resp.read()
            scheme, host, path, params, query, fragment \
                    = urlparse.urlparse(location)
            if scheme == "http":    is_secure = True
            elif scheme == "https": is_secure = False
            else: raise S3Exception("Not http/https: " + location)
            if query: path += "?" + query

    def _make_request(self, conf, post_params={}):
        """Make a request to the API and return data in a pythonic object"""
        endpoint, requires_auth = conf

        # setup the url and the request objects
        url = '%s%s.php' % (self.api_url, endpoint)
        log.debug('Setting url to %s' % url)
        request = urllib2.Request(url)

        # tack on authentication if needed
        log.debug('Post params: %s' % post_params)
        if requires_auth:
            post_params.update({
                'user': self.username,
                'pass': self.password
            })

        # url encode all parameters
        data = urlencode(post_params).encode('utf-8')

        # gimme some bitcoins!
        try:
            log.debug('Requesting data from %s' % url)
            response = urllib2.urlopen(request, data)
            return json.loads(response.read())
        except urllib2.URLError as e:
            log.debug('Full error: %s' % e)
            if hasattr(e, 'reason'):
                self.log.error('Could not reach host. Reason: %s' % e.reason)
            elif hasattr(e, 'code'):
                self.log.error('Could not fulfill request. Error Code: %s' % e.code)
            return None

    def _make_request(self, action, params=None):
        """Make a call to the SES API.

        :type action: string
        :param action: The API method to use (e.g. SendRawEmail)

        :type params: dict
        :param params: Parameters that will be sent as POST data with the API
            call.
        """
        ct = 'application/x-www-form-urlencoded; charset=UTF-8'
        headers = {'Content-Type': ct}
        params = params or {}
        params['Action'] = action

        for k, v in params.items():
            if isinstance(v, six.text_type):  # UTF-8 encode only if it's Unicode
                params[k] = v.encode('utf-8')

        response = super(SESConnection, self).make_request(
            'POST',
            '/',
            headers=headers,
            data=urllib.parse.urlencode(params)
        )
        body = response.read().decode('utf-8')
        if response.status == 200:
            list_markers = ('VerifiedEmailAddresses', 'Identities',
                            'DkimTokens', 'DkimAttributes',
                            'VerificationAttributes', 'SendDataPoints')
            item_markers = ('member', 'item', 'entry')

            e = boto.jsonresponse.Element(list_marker=list_markers,
                                          item_marker=item_markers)
            h = boto.jsonresponse.XmlHandler(e, None)
            h.parse(body)
            return e
        else:
            # HTTP codes other than 200 are considered errors. Go through
            # some error handling to determine which exception gets raised,
            self._handle_error(response, body)

    def _make_request(self, method, bucket='', key='', query_args={}, headers={}, data='', metadata={}):

        server = ''
        if bucket == '':
            server = self.server
        elif self.calling_format == CallingFormat.SUBDOMAIN:
            server = "%s.%s" % (bucket, self.server)
        elif self.calling_format == CallingFormat.VANITY:
            server = bucket
        else:
            server = self.server

        path = ''

        if (bucket != '') and (self.calling_format == CallingFormat.PATH):
            path += "/%s" % bucket

        # add the slash after the bucket regardless
        # the key will be appended if it is non-empty
        path += "/%s" % urllib.parse.quote_plus(key)


        # build the path_argument string
        # add the ? in all cases since 
        # signature and credentials follow path args
        if len(query_args):
            path += "?" + query_args_hash_to_string(query_args)

        is_secure = self.is_secure
        host = "%s:%d" % (server, self.port)
        while True:
            if (is_secure):
                connection = http.client.HTTPSConnection(host)
            else:
                connection = http.client.HTTPConnection(host)

            final_headers = merge_meta(headers, metadata)
            # add auth header
            self._add_aws_auth_header(final_headers, method, bucket, key, query_args)

            connection.request(method, path, data, final_headers)
            resp = connection.getresponse()
            if resp.status < 300 or resp.status >= 400:
                return resp
            # handle redirect
            location = resp.getheader('location')
            if not location:
                return resp
            # (close connection)
            resp.read()
            scheme, host, path, params, query, fragment \
                    = urllib.parse.urlparse(location)
            if scheme == "http":    is_secure = True
            elif scheme == "https": is_secure = False
            else: raise IOError("Not http/https: " + location)
            if query: path += "?" + query

    def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)

        try:
            timeout_obj.start_connect()
            conn.timeout = timeout_obj.connect_timeout
            # conn.request() calls httplib.*.request, not the method in
            # urllib3.request. It also calls makefile (recv) on the socket.
            conn.request(method, url, **httplib_request_kw)
        except SocketTimeout:
            raise ConnectTimeoutError(
                self, "Connection to %s timed out. (connect timeout=%s)" %
                (self.host, timeout_obj.connect_timeout))

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if hasattr(conn, 'sock'):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url,
                    "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else: # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try: # Python 2.7+, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError: # Python 2.6 and older
                httplib_response = conn.getresponse()
        except SocketTimeout:
            raise ReadTimeoutError(
                self, url, "Read timed out. (read timeout=%s)" % read_timeout)

        except BaseSSLError as e:
            # Catch possible read timeouts thrown as SSL errors. If not the
            # case, rethrow the original. We need to do this because of:
            # http://bugs.python.org/issue10272
            if 'timed out' in str(e) or \
               'did not complete (read)' in str(e):  # Python 2.6
                raise ReadTimeoutError(self, url, "Read timed out.")

            raise

        except SocketError as e: # Platform-specific: Python 2
            # See the above comment about EAGAIN in Python 3. In Python 2 we
            # have to specifically catch it and throw the timeout error
            if e.errno in _blocking_errnos:
                raise ReadTimeoutError(
                    self, url,
                    "Read timed out. (read timeout=%s)" % read_timeout)

            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
                                          httplib_response.status,
                                          httplib_response.length))
        return httplib_response

    def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        """
        Perform a request on a given httplib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)

        try:
            timeout_obj.start_connect()
            conn.timeout = timeout_obj.connect_timeout
            # conn.request() calls httplib.*.request, not the method in
            # urllib3.request. It also calls makefile (recv) on the socket.
            conn.request(method, url, **httplib_request_kw)
        except SocketTimeout:
            raise ConnectTimeoutError(
                self, "Connection to %s timed out. (connect timeout=%s)" %
                (self.host, timeout_obj.connect_timeout))

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if hasattr(conn, 'sock'):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url,
                    "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else: # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try: # Python 2.7+, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError: # Python 2.6 and older
                httplib_response = conn.getresponse()
        except SocketTimeout:
            raise ReadTimeoutError(
                self, url, "Read timed out. (read timeout=%s)" % read_timeout)

        except BaseSSLError as e:
            # Catch possible read timeouts thrown as SSL errors. If not the
            # case, rethrow the original. We need to do this because of:
            # http://bugs.python.org/issue10272
            if 'timed out' in str(e) or \
               'did not complete (read)' in str(e):  # Python 2.6
                raise ReadTimeoutError(self, url, "Read timed out.")

            raise

        except SocketError as e: # Platform-specific: Python 2
            # See the above comment about EAGAIN in Python 3. In Python 2 we
            # have to specifically catch it and throw the timeout error
            if e.errno in _blocking_errnos:
                raise ReadTimeoutError(
                    self, url,
                    "Read timed out. (read timeout=%s)" % read_timeout)

            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
                                          httplib_response.status,
                                          httplib_response.length))
        return httplib_response

    def _make_request(self, method, path, **kwargs):
        """Make request. Generally not called directly.

        :param method: HTTP Method
        :param path: resource Path
        :param dict \\*\\*kwargs: extra request arguments
        """
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': consts.USER_AGENT,
        }
        headers.update(kwargs.get('headers', {}))
        kwargs['headers'] = headers
        kwargs['auth'] = self.auth

        url = '/'.join((self.endpoint, 'v1', self.account_id, path))
        resp = requests.request(method, url, **kwargs)
        try:
            resp.raise_for_status()
        except requests.HTTPError as ex:
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['message'])
        return resp

    def _make_request(self, path, data = None, method = 'POST', files = None):
        if data is None:
            data = {}

        headers = {
            'User-Agent': 'Snapchat/8.1.1 (iPhone5,1; iOS 8.1.3; gzip)',
            'Accept-Language': 'en-US;q=1, en;q=0.9',
            'Accept-Locale': 'en'
        }

        now = timestamp()

        if method == 'POST':
            data['timestamp'] = now
            data['req_token'] = make_request_token(self.auth_token, str(now))
            resp = requests.post(BASE_URL + path, data = data, files = files, headers = headers)
        else:
            resp = requests.get(BASE_URL + path, params = data, headers = headers)

        return resp

    def _make_request(self, request, uri, **kwargs):
        """
        This is final step of calling out to the remote API.  We set up our
        headers, proxy, debugging etc. The only things in **kwargs are
        parameters that are overridden on an API method basis (like timeout)

        We have a simple attempt/while loop to implement retries w/ delays to
        avoid the brittleness of talking over the network to remote services.
        These settings can be overridden when creating the Client.

        We catch the 'requests' exceptions during our retries and eventually
        raise our own NewRelicApiException if we are unsuccessful in contacting
        the New Relic API. Additionally we process any non 200 HTTP Errors
        and raise an appropriate exception according to the New Relic API
        docuementation.

        Finally we pass back the response text to our XML parser since we have
        no business parsing that here. It could be argued that handling API
        exceptions/errors shouldn't belong in this method but it is simple
        enough for now.
        """
        attempts = 0
        response = None
        while attempts <= self.retries:
            try:
                response = request(uri, headers=self.headers, proxies=self.proxy, **kwargs)

            except (requests.ConnectionError, requests.HTTPError) as ce:
                attempts += 1
                msg = "Attempting retry {attempts} after {delay} seconds".format(attempts=attempts, delay=self.retry_delay)
                logger.error(ce.__doc__)
                logger.error(msg)
                sleep(self.retry_delay)
            else:
                break
        if response is not None:
            try:
                response.raise_for_status()
            except Exception as e:
                self._handle_api_error(e)
        else:
            raise requests.RequestException
        return self._parser(response.text)

    def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        try:
            self._validate_conn(conn)
        except (SocketTimeout, BaseSSLError) as e:
            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
            raise

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        if chunked:
            conn.request_chunked(method, url, **httplib_request_kw)
        else:
            conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older, Python 3
                try:
                    httplib_response = conn.getresponse()
                except Exception as e:
                    # Remove the TypeError from the exception chain in Python 3;
                    # otherwise it looks like a programming error was the cause.
                    six.raise_from(e, None)
        except (SocketTimeout, BaseSSLError, SocketError) as e:
            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("%s://%s:%s \"%s %s %s\" %s %s", self.scheme, self.host, self.port,
                  method, url, http_version, httplib_response.status,
                  httplib_response.length)

        try:
            assert_header_parsing(httplib_response.msg)
        except HeaderParsingError as hpe:  # Platform-specific: Python 3
            log.warning(
                'Failed to parse headers (url=%s): %s',
                self._absolute_url(url), hpe, exc_info=True)

        return httplib_response

    def _make_request(self, url):
        # By constructing the request outside the Session, we avoid attaching
        # unwanted cookie headers to subsequent requests, which might break the
        # cache.
        return requests.Request('GET', url).prepare()

    @retry(Exception, tries=3)
    def _make_request(self, url, params=None, opener=None):
        """
        Configure a HTTP request, fire it off and return the response.
        """
        # Create the request object
        args = [i for i in [url, params] if i]
        request = urllib.request.Request(*args)
        # If the client has credentials, include them as a header
        if self.username and self.password:
            credentials = '%s:%s' % (self.username, self.password)
            encoded_credentials = base64.encodestring(
                credentials.encode("utf-8")
            ).decode("utf-8").replace("\n", "")
            header = 'Basic %s' % encoded_credentials
            request.add_header('Authorization', header)
        # If the request provides a custom opener, like the upload request,
        # which relies on a multipart request, it is applied here.
        if opener:
            opener = urllib.request.build_opener(opener)
            request_method = opener.open
        else:
            request_method = urllib.request.urlopen
        # Make the request
        try:
            response = request_method(request)
        except:
            e = sys.exc_info()[1]
            if getattr(e, 'code', None) == 404:
                raise DoesNotExistError("The resource you've requested does \
not exist or is unavailable without the proper credentials.")
            elif getattr(e, 'code', None) == 401:
                raise CredentialsFailedError("The resource you've requested \
requires proper credentials.")
            else:
                raise e
        # Read the response and return it
        return response.read()

    def _make_request(self, method, url, allow_redirects, timeout, **kwargs):
        try:
            resp = requests.request(
                method,
                self.endpoint_url + url,
                allow_redirects=allow_redirects,
                timeout=timeout,
                **kwargs)
        except socket.gaierror as e:
            message = ("Error finding address for %(url)s: %(e)s" %
                       {'url': self.endpoint_url + url, 'e': e})
            raise exc.InvalidEndpoint(message=message)
        except (socket.error, socket.timeout) as e:
            endpoint = self.endpoint
            message = ("Error communicating with %(endpoint)s %(e)s" %
                       {'endpoint': endpoint, 'e': e})
            raise exc.CommunicationError(message=message)
        except requests.Timeout as e:
            endpoint = self.endpoint
            message = ("Error %(method)s timeout request to %(endpoint)s %(e)s" %
                       {'method': method, 'endpoint': endpoint, 'e': e})
            raise exc.RequestTimeoutError(message=message)
        except requests.ConnectionError as ex:
            endpoint = self.endpoint
            message = ("Failed to connect to %s, error was %s" % (endpoint, ex.message))
            raise exc.CommunicationError(message=message)
        self.log_http_response(resp)
        return resp

    def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        try:
            self._validate_conn(conn)
        except (SocketTimeout, BaseSSLError) as e:
            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
            raise

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        if chunked:
            conn.request_chunked(method, url, **httplib_request_kw)
        else:
            conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older
                httplib_response = conn.getresponse()
        except (SocketTimeout, BaseSSLError, SocketError) as e:
            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s", method, url, http_version,
                  httplib_response.status, httplib_response.length)

        try:
            assert_header_parsing(httplib_response.msg)
        except HeaderParsingError as hpe:  # Platform-specific: Python 3
            log.warning(
                'Failed to parse headers (url=%s): %s',
                self._absolute_url(url), hpe, exc_info=True)

        return httplib_response

	def _make_request( self, loc, headers, data = None, retry = True ):
		last_e = None
		utserver_retry = False
		retries = 0
		max_retries = self._retry_max if retry else 1
		try:
			while retries < max_retries or utserver_retry:
				try:
					self._request.data = data
					self._connection.request( self._request.get_method( ), self._request.selector + loc, self._request.data, headers )
					resp = self._connection.getresponse( )
					if resp.status == 400:
						last_e = utorrent.uTorrentError( resp.read( ).decode( "utf8" ).strip( ) )
						# if uTorrent server alpha is bound to the same port as WebUI then it will respond with "invalid request" to the first request in the connection
						# apparently this is no longer the case, TODO: remove this hack
						if ( not self._utorrent or type( self._utorrent ) == utorrent.uTorrent.LinuxServer ) and not utserver_retry:
							utserver_retry = True
							continue
						raise last_e
					elif resp.status == 404 or resp.status == 401:
						raise utorrent.uTorrentError( "Request {}: {}".format( loc, resp.reason ) )
					elif resp.status != 200 and resp.status != 206:
						raise utorrent.uTorrentError( "{}: {}".format( resp.reason, resp.status ) )
					self._cookies.extract_cookies( resp, self._request )
					if len( self._cookies ) > 0:
						self._request.add_header( "Cookie", "; ".join(
							["{}={}".format( utorrent._url_quote( c.name ), utorrent._url_quote( c.value ) ) for c in self._cookies] ) )
					return resp
				# retry when utorrent returns bad data
				except ( http.client.CannotSendRequest, http.client.BadStatusLine ) as e:
					last_e = e
					self._connection.close( )
				# name resolution failed
				except socket.gaierror as e:
					raise utorrent.uTorrentError( e.strerror )
				# socket errors
				except socket.error as e:
					# retry on timeout
					if str( e ) == "timed out": # some peculiar handling for timeout error
						last_e = utorrent.uTorrentError( "Timeout after {} tries".format( max_retries ) )
						self._connection.close( )
					# retry after pause on specific windows errors
					elif e.errno == 10053 or e.errno == 10054:
						# Windows specific socket errors:
						# 10053 - An established connection was aborted by the software in your host machine
						# 10054 - An existing connection was forcibly closed by the remote host
						last_e = e
						self._connection.close( )
						time.sleep( 2 )
					elif e.errno == errno.ECONNREFUSED or e.errno == errno.ECONNRESET or errno == errno.EHOSTUNREACH:
						raise utorrent.uTorrentError( e.strerror )
					else:
						raise e
				retries += 1
			if last_e:
				raise last_e
		except Exception as e:
			self._connection.close( )
			raise e
		return None

    def _make_request(self, url, method, payload=None, headers=None):
        """
        A wrapper around httplib2.Http.request.

        Required Arguments:

            url
                The url of the request.

            method
                The method of the request. I.e. 'GET', 'PUT', 'POST', 'DELETE'.

        Optional Arguments:

            payload
                The urlencoded parameters.

            headers
                Additional headers of the request.

        """
        if payload is None:
            if self._meta.serialize:
                payload = self._serialize({})
            else:
                payload = urlencode({})
        if headers is None:
            headers = {}

        try:
            http = self._get_http()
            return http.request(url, method, payload, headers=headers)

        except socket.error as e:
            # Try again just in case there was an issue with the cached _http
            try:
                self._clear_http()
                return self._get_http().request(url, method, payload,
                                                headers=headers)
            except socket.error as e:
                raise exc.dRestAPIError(e)

        except ServerNotFoundError as e:
            raise exc.dRestAPIError(e.args[0])

    def _make_request(self, url, parameters, result_key):
        """Make http/https request to Google API.

        Method prepares url parameters, drops None values, and gets default
        values. Finally makes request using protocol assigned to client and
        returns data.

        :param url: url part - specifies API endpoint
        :param parameters: dictionary of url parameters
        :param result_key: key in output where result is expected
        """
        url = urlparse.urljoin(urlparse.urljoin(self.base, url), "json")

        # drop all None values and use defaults if not set
        parameters = {key: value for key, value in parameters.items() if
                      value is not None}
        parameters.setdefault("sensor", self.sensor)
        parameters = self._serialize_parameters(parameters)
        if self.api_key:
            parameters["key"] = self.api_key

        raw_response = requests.get(url, params=parameters)
        response = raw_response.json()

        if response["status"] == status.OK and result_key is not None:
            return response[result_key]
        elif response["status"] == status.OK:
            del response["status"]
            return response
        else:
            response["url"] = raw_response.url
            raise errors.EXCEPTION_MAPPING.get(
                response["status"],
                errors.GmapException
            )(response)

    def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        try:
            self._validate_conn(conn)
        except (SocketTimeout, BaseSSLError) as e:
            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
            raise

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older
                httplib_response = conn.getresponse()
        except (SocketTimeout, BaseSSLError, SocketError) as e:
            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
                                          httplib_response.status,
                                          httplib_response.length))
        return httplib_response

    def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        try:
            self._validate_conn(conn)
        except (SocketTimeout, BaseSSLError) as e:
            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
            raise

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        if chunked:
            conn.request_chunked(method, url, **httplib_request_kw)
        else:
            conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older, Python 3
                try:
                    httplib_response = conn.getresponse()
                except Exception as e:
                    # Remove the TypeError from the exception chain in Python 3;
                    # otherwise it looks like a programming error was the cause.
                    six.raise_from(e, None)
        except (SocketTimeout, BaseSSLError, SocketError) as e:
            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s", method, url, http_version,
                  httplib_response.status, httplib_response.length)

        try:
            assert_header_parsing(httplib_response.msg)
        except HeaderParsingError as hpe:  # Platform-specific: Python 3
            log.warning(
                'Failed to parse headers (url=%s): %s',
                self._absolute_url(url), hpe, exc_info=True)

        return httplib_response

    def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        try:
            self._validate_conn(conn)
        except (SocketTimeout, BaseSSLError) as e:
            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
            raise

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7+, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older
                httplib_response = conn.getresponse()
        except (SocketTimeout, BaseSSLError, SocketError) as e:
            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
                                          httplib_response.status,
                                          httplib_response.length))
        return httplib_response

    def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        """
        Perform a request on a given urllib connection object taken from our
        pool.

        :param conn:
            a connection from one of our connection pools

        :param timeout:
            Socket timeout in seconds for the request. This can be a
            float or integer, which will set the same timeout value for
            the socket connect and the socket read, or an instance of
            :class:`urllib3.util.Timeout`, which gives you more fine-grained
            control over your timeouts.
        """
        self.num_requests += 1

        timeout_obj = self._get_timeout(timeout)
        timeout_obj.start_connect()
        conn.timeout = timeout_obj.connect_timeout

        # Trigger any extra validation we need to do.
        self._validate_conn(conn)

        # conn.request() calls httplib.*.request, not the method in
        # urllib3.request. It also calls makefile (recv) on the socket.
        conn.request(method, url, **httplib_request_kw)

        # Reset the timeout for the recv() on the socket
        read_timeout = timeout_obj.read_timeout

        # App Engine doesn't have a sock attr
        if getattr(conn, 'sock', None):
            # In Python 3 socket.py will catch EAGAIN and return None when you
            # try and read into the file pointer created by http.client, which
            # instead raises a BadStatusLine exception. Instead of catching
            # the exception and assuming all BadStatusLine exceptions are read
            # timeouts, check for a zero timeout before making the request.
            if read_timeout == 0:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)
            if read_timeout is Timeout.DEFAULT_TIMEOUT:
                conn.sock.settimeout(socket.getdefaulttimeout())
            else:  # None or a value
                conn.sock.settimeout(read_timeout)

        # Receive the response from the server
        try:
            try:  # Python 2.7+, use buffering of HTTP responses
                httplib_response = conn.getresponse(buffering=True)
            except TypeError:  # Python 2.6 and older
                httplib_response = conn.getresponse()
        except SocketTimeout:
            raise ReadTimeoutError(
                self, url, "Read timed out. (read timeout=%s)" % read_timeout)

        except BaseSSLError as e:
            # Catch possible read timeouts thrown as SSL errors. If not the
            # case, rethrow the original. We need to do this because of:
            # http://bugs.python.org/issue10272
            if 'timed out' in str(e) or \
               'did not complete (read)' in str(e):  # Python 2.6
                raise ReadTimeoutError(
                        self, url, "Read timed out. (read timeout=%s)" % read_timeout)

            raise

        except SocketError as e:  # Platform-specific: Python 2
            # See the above comment about EAGAIN in Python 3. In Python 2 we
            # have to specifically catch it and throw the timeout error
            if e.errno in _blocking_errnos:
                raise ReadTimeoutError(
                    self, url, "Read timed out. (read timeout=%s)" % read_timeout)

            raise

        # AppEngine doesn't have a version attr.
        http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
        log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
                                          httplib_response.status,
                                          httplib_response.length))
        return httplib_response