request

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

981 Examples 7

3
File: http.py, Project: blueprint, View license
uses: errno.EPIPE
def _request(verb, path, body=None, headers={}, server=None):
    c = _connect(server)
    try:
        c.request(verb, path, body, headers)
    except socket.error as e:
        if errno.EPIPE != e.errno:
            raise e
    return c.getresponse()

    def _request(self, method, url, **kwargs):
        try:
            self._logger.debug("Requesting %s with args %s", url, kwargs.get('params') or kwargs.get('data'))
            return requests.request(method, url, timeout=self._http_timeout, **kwargs)
        except requests.exceptions.SSLError:
            self._logger.warning("Retrying %s without SSL verification", url)
            return requests.request(method, url, timeout=self._http_timeout, verify=False, **kwargs)

def _request(uri):
    """
    Just a wrapper around the request.get() function
    """

    r = requests.get(uri)

    if r.status_code == 200:
        return _to_json(r.text)
    else:
        raise ResourceNotFoundError(
            'API responded with %s error' % str(r.status_code))

    def __request(self, methodname, params):
        # call a method on the remote server
    
        request = xmlrpc.client.dumps(params, methodname, encoding=self.__encoding,
                                  allow_none=self.__allow_none)
    
        response = self.__transport.request(
            self.__host,
            self.__handler,
            request,
            verbose=self.__verbose
            )
    
        if len(response) == 1:
            response = response[0]
    
        return response

    def __request(self, method, path, headers=None, data=None):
        url = self.__get_full_url(path)
        req = requests.request(method, url, headers=headers, data=data)
        if 200 <= req.status_code < 300:
            resp = req.content
            self.log.debug("'%s' response %d from alauda api '%s': %s" % (method, req.status_code, path, resp))
            return resp
        else:
            self.log.debug("'%s' from alauda api '%s' failed: %s, %s" % (method, path, req.status_code, req.content))
            raise AlaudaException(req.status_code, req.content)

def __request(url, key):
    '''
    Make a request to the Github api.
    '''
    try:
        auth = requests.auth.HTTPBasicAuth(key, 'x-oauth-basic')        
        resp = requests.get(url, auth=auth)

        if resp.status_code == 200:
            return resp.json()
        else:
            return None

    except Exception as e:
        logger.error(e)
        return None

3
File: s3iam.py, Project: yum-s3-iam, View license
uses: urllib2.quote
    def _request(self, path, timeval=None):
        url = urlparse.urljoin(self.baseurl, urllib2.quote(path))
        request = urllib2.Request(url)
        if self.region:
            self.signV4(request, timeval)
        else:
            self.signV2(request, timeval)
        return request

    def __request(self, method, path, **kwargs):
        url = self.base_url + path
        if not self.api_key:
            raise AttributeError('api_key not yet set')
        kwargs.setdefault('params', dict()).update(key=self.api_key)
        return requests.request(method, url, **kwargs).json()

3
File: scgi.py, Project: SickGear, View license
uses: xmlrpclib.dumps
    def __request(self, methodname, params):
        # call a method on the remote server

        request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding,
                                  allow_none=self.__allow_none)

        response = self.__transport.request(
            self.__host,
            self.__handler,
            request,
            verbose=self.__verbose
        )

        if len(response) == 1:
            response = response[0]

        return response

    def __request(self, relative_url=None):
        "Perform the pending request."
        if self.fakeheaders:
            self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
        if relative_url:
            self.set_option(pycurl.URL, urljoin(self.base_url, relative_url))
        self.payload = ""
        self.hdr = ""
        self.handle.perform()
        return self.payload

    def _request(self, request, _callback, async=False):
        if async:
            return httpclient.AsyncHTTPClient().fetch(request, _callback)
        else:
            try:
                response = httpclient.HTTPClient().fetch(request)
            except httpclient.HTTPError, e:
                response = e.response
            return _callback(response)

    def __request(self, method_name, params):
        # call a method on the remote server

        request = xmlrpc_client.dumps(params, method_name, encoding=self.__encoding,
                                      allow_none=self.__allow_none).encode(self.__encoding)

        response = self.__transport.request(
            self.__host,
            self.__handler,
            request.decode('utf-8'),
            verbose=self.__verbose
        )

        if len(response) == 1:
            response = response[0]

        return response

    def __request(self, relative_url=None):
        "Perform the pending request."
        if self.fakeheaders:
            self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
        if relative_url:
            self.set_option(pycurl.URL, urljoin(self.base_url, relative_url))
        self.payload = None
        self.hdr = ""
        self.handle.perform()
        self.payload = self.payload_io.getvalue()
        return self.payload

3
File: web_test.py, Project: torus, View license
uses: ujson.dumps
  def _request(self, request):
    '''
    Helper to make a request and confirm that it can be encoded. Needed
    until this test actually starts a webserver and queries it.
    '''
    result = web._series(request)
    ujson.dumps( result, double_precision=4 )
    return result

    def __request(self, method, url, user, password, data=None):
        ksclient = v2_0.Client(
            auth_url=magic_consts.KEYSTONE_API_URL,
            username=user,
            password=password,
            tenant_name=magic_consts.KEYSTONE_TENANT_NAME,
        )
        resp = requests.request(
            method,
            urlparse.urljoin(magic_consts.NAILGUN_URL, url),
            json=data,
            headers={
                "X-Auth-Token": ksclient.auth_token,
                "Content-Type": "application/json",
            })
        LOG.debug(resp.content)
        return resp

    def __request(self, methodname, params):
        ITERS = 10
        for i in range(ITERS):
            try:
                return xmlrpclib.ServerProxy.__request(self, methodname, params)
            except xmlrpclib.ProtocolError as e:
                if e.errcode != 500:
                    raise
            except socket.error as e:
                pass
            if i < ITERS-1:
                if self.verbose_timeout:
                    print >> sys.stderr, _('Server Error, retrying in %d seconds') % ((i+1)**2)
                time.sleep((i+1)**2)
            else:
                if self.verbose_timeout:
                    print >> sys.stderr, _('Server Error, aborting')
                raise e

    def __request(self, relative_url=None):
        """
        Perform a request and returns the payload.
        """
        if self.fakeheaders:
            from XSSer.randomip import RandomIP
            if self.xforw:
                """
                Set the X-Forwarded-For to use.
                """
                generate_random_xforw = RandomIP()
                xforwip = generate_random_xforw._generateip('')
                #xforwip = '127.0.0.1'
                xforwfakevalue = ['X-Forwarded-For: ' + str(xforwip)]
            if self.xclient:
                """ 
                Set the X-Client-IP to use.
                """
                generate_random_xclient = RandomIP()
                xclientip = generate_random_xclient._generateip('')
                #xclientip = '127.0.0.1'
                xclientfakevalue = ['X-Client-IP: ' + str(xclientip)]
            if self.xforw:
                self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue)
                if self.xclient:
                    self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue + xclientfakevalue)
            elif self.xclient:
                self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xclientfakevalue)
        if self.headers:
            # XXX sanitize user input
            self.fakeheaders = self.fakeheaders + self.headers
        self.set_option(pycurl.HTTPHEADER, self.fakeheaders)

        if self.agent:
            self.set_option(pycurl.USERAGENT, self.agent)
        if self.referer:
            self.set_option(pycurl.REFERER, self.referer)
        if self.proxy:
            self.set_option(pycurl.PROXY, self.proxy)
        if self.ignoreproxy:
            self.set_option(pycurl.PROXY, "")
        if relative_url:
            self.set_option(pycurl.URL,os.path.join(self.base_url,relative_url))
        if self.timeout:
            self.set_option(pycurl.CONNECTTIMEOUT, self.timeout)
            self.set_option(pycurl.TIMEOUT, self.timeout)
        if self.signals:
            self.set_option(pycurl.NOSIGNAL, self.signals)
        if self.tcp_nodelay:
            self.set_option(pycurl.TCP_NODELAY, self.tcp_nodelay)
        if self.cookie:
            self.set_option(pycurl.COOKIE, self.cookie)
        if self.followred:
            self.set_option(pycurl.FOLLOWLOCATION , 1)
            self.set_option(pycurl.MAXREDIRS, 50)
            if self.fli:
                self.set_option(pycurl.MAXREDIRS, int(self.fli))
        else:
            self.set_option(pycurl.FOLLOWLOCATION , 0)
            if self.fli:
                print "\n[E] You must launch --follow-redirects command to set correctly this redirections limit\n"
                return
        """ 
        Set the HTTP authentication method: Basic, Digest, GSS, NTLM or Certificate
        """
        if self.atype and self.acred:
            atypelower = self.atype.lower()
            if atypelower not in ( "basic", "digest", "ntlm", "gss" ):
                print "\n[E] HTTP authentication type value must be: Basic, Digest, GSS or NTLM\n"
                return
            acredregexp = re.search("^(.*?)\:(.*?)$", self.acred)
            if not acredregexp:
                print "\n[E] HTTP authentication credentials value must be in format username:password\n"
                return
            user = acredregexp.group(1)
            password = acredregexp.group(2)
            self.set_option(pycurl.USERPWD, "%s:%s" % (user,password))

            if atypelower == "basic":
                self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
            elif atypelower == "digest":
                self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
            elif atypelower == "ntlm":
                self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
            elif atypelower == "gss":
                self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_GSSNEGOTIATE)
            else:
                self.set_option(pycurl.HTTPAUTH, None)

            self.set_option(pycurl.HTTPHEADER, ["Accept:"])

        elif self.atype and not self.acred:
            print "\n[E] You specified the HTTP authentication type, but did not provide the credentials\n"
            return
        elif not self.atype and self.acred:
            print "\n[E] You specified the HTTP authentication credentials, but did not provide the type\n"
            return
        #if self.acert:
        #    acertregexp = re.search("^(.+?),\s*(.+?)$", self.acert)
        #    if not acertregexp:
        #        print "\n[E] HTTP authentication certificate option must be 'key_file,cert_file'\n"
        #        return
        #    # os.path.expanduser for support of paths with ~
        #    key_file = os.path.expanduser(acertregexp.group(1))
        #    cert_file = os.path.expanduser(acertregexp.group(2))
        #    self.set_option(pycurl.SSL_VERIFYHOST, 0)
        #    self.set_option(pycurl.SSL_VERIFYPEER, 1)
        #    self.set_option(pycurl.SSH_PUBLIC_KEYFILE, key_file)
        #    self.set_option(pycurl.CAINFO, cert_file)
        #    self.set_option(pycurl.SSLCERT, cert_file)
        #    self.set_option(pycurl.SSLCERTTYPE, 'p12')
        #    self.set_option(pycurl.SSLCERTPASSWD, '1234')
        #    self.set_option(pycurl.SSLKEY, key_file)
        #    self.set_option(pycurl.SSLKEYPASSWD, '1234')
        #    for file in (key_file, cert_file):
        #        if not os.path.exists(file):
        #            print "\n[E] File '%s' doesn't exist\n" % file
        #            return
        
        self.set_option(pycurl.SSL_VERIFYHOST, 0)
        self.set_option(pycurl.SSL_VERIFYPEER, 0)

        self.header.seek(0,0)
        self.payload = ""

        for count in range(0, self.retries):
            time.sleep(self.delay)
            if self.dropcookie:
                self.set_option(pycurl.COOKIELIST, 'ALL')
                nocookie = ['Set-Cookie: ', '']
                self.set_option(pycurl.HTTPHEADER, self.fakeheaders + nocookie)
            try:
                self.handle.perform()
            except:
                return
        return self.payload

    def _request(self, function, params):
        """General-purpose function to create web requests to SHODAN.
        
        Arguments:
        function  -- name of the function you want to execute
        params      -- dictionary of parameters for the function
        
        Returns
        A JSON string containing the function's results.
        
        """
        # Add the API key parameter automatically
        params['key'] = self.api_key
        
        # Send the request
        data = urlopen(self.base_url + function + '?' + urlencode(params)).read().decode('utf-8')
        
        # Parse the text into JSON
        data = loads(data)
        
        # Raise an exception if an error occurred
        if data.get('error', None):
            raise WebAPIError(data['error'])
        
        # Return the data
        return data

    def _request(self, location="", method="GET", query_args={}, form_data={}):
        """Send request to deltacloud and return a response dom object.

        The returned dom object should be unlinked after it's done being used:
        >>> dom = self._request("/some/path")
        >>> dom.unlink()

        """
        headers = {
            "Accept": "text/xml",
            "Authorization": self._auth_string,
        }

        # Handle both absolute and relative urls
        matches = Deltacloud.url_regex.match(location)
        if matches == None: # Relative
            host = self.api_entry_host
            path = location
        else: # Absolute
            host = matches.group(1)
            path = matches.group(2)

        # Format query_string
        query_list = map(lambda key,value: key+"="+value,
                         query_args.keys(),
                         query_args.values()
                        )
        if query_list:
            query_string = '?'+'&'.join(query_list)
        else:
            query_string = ""

        # Handle form_data
        if method=="POST" and form_data:
            # Thanks for the good form data example at:
            # http://code.google.com/p/urllib3/source/browse/urllib3/filepost.py
            BOUNDARY = mimetools.choose_boundary()
            body = ""
            for key, value in form_data.iteritems():
                body += ENCODE_TEMPLATE % {
                    'boundary': BOUNDARY,
                    'name': str(key),
                    'value': str(value),
                }
            body += "--%s--\n\r" % BOUNDARY
            content_type = "multipart/form-data; boundary=%s" % BOUNDARY
            headers['Content-Type'] = content_type
        else:
            body = None

        # The actual request
        #print (host, method, path+query_string, body, headers)
        if self.secure:
            connection = httplib.HTTPSConnection(host)
        else:
            connection = httplib.HTTPConnection(host)
        connection.request(method, path+query_string, body=body, headers=headers)
        response = connection.getresponse()
        connection.close()
        text = response.read()
        #print text
        if response.status < 200 or response.status >= 400:
            # Response was not successful (status 2xx or 3xx).  3xx is included
            # because sometimes deltacloud returns a redirect even when the
            # action is completed.
            #TODO: Handle error better
            raise ValueError("Status code returned by deltacloud was %s." % response.status)
        try:
            return parseString(text)
        except Exception:
            log.error("There was a problem parsing XML from deltacloud!")
            raise

    def __request(self, method, url, headers=None, **kwargs):
        url = urljoin(self._url, url)

        if not headers:
            headers = {}

        if self.token:
            headers['X-Vault-Token'] = self.token

        wrap_ttl = kwargs.pop('wrap_ttl', None)
        if wrap_ttl:
            headers['X-Vault-Wrap-TTL'] = str(wrap_ttl)

        _kwargs = self._kwargs.copy()
        _kwargs.update(kwargs)

        response = self.session.request(method, url, headers=headers,
                                        allow_redirects=False, **_kwargs)

        # NOTE(ianunruh): workaround for https://github.com/ianunruh/hvac/issues/51
        while response.is_redirect and self.allow_redirects:
            url = urljoin(self._url, response.headers['Location'])
            response = self.session.request(method, url, headers=headers,
                                            allow_redirects=False, **_kwargs)

        if response.status_code >= 400 and response.status_code < 600:
            text = errors = None
            if response.headers.get('Content-Type') == 'application/json':
                errors = response.json().get('errors')
            if errors is None:
                text = response.text
            self.__raise_error(response.status_code, text, errors=errors)

        return response

    def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
        if log.isEnabledFor(logging.DEBUG):
            body_str = body or '(none)'
            if body and len(body) > 1024:
                body_str = body[:1021] + '...'
            log.debug("req: %s %s\n%s", method, request_uri,
                '\n'.join([
                    _indent("host: " + host),
                    _indent("headers: " + pformat(headers)),
                    #_indent("cachekey: " + pformat(cachekey)), #XXX
                    _indent("body: " + body_str)
                ]))
        res, content = httplib2.Http._request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey)
        if log.isEnabledFor(logging.DEBUG):
            ucontent = content.decode('utf-8')
            log.debug("res: %s %s\n%s\n%s", method, request_uri,
                _indent(pformat(res)),
                (len(ucontent) < 1024 and _indent(ucontent)
                 or _indent(ucontent[:1021] + u'...')))
        return (res, content)

    def _request(self, method='get', params={}, data=None, files=None):
        response = None
        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        logger.log(
            self.name + u': Requested a ' + method.upper() +
            ' connection to url ' + self.url + ' with Params= ' + str(params) +
            ' Data=' + str(data if data else 'None')[0:99] +
            ('...' if len(data if data else 'None') > 200 else ''),
            logger.DEBUG
        )

        logger.log(
            self.name + u': Requested a ' + method.upper() +
            ' connection to url ' + self.url + ' with Params= ' + str(params) +
            ((' Data=' + str(data)[0:100] + ('...' if len(data) > 100 else ''))
             if data is not None else ''),
            logger.DEBUG
        )

        if not self.auth:
            logger.log(self.name + u': Authentication Failed', logger.ERROR)
            return False
        try:
            response = self.session.__getattribute__(method)(self.url, params=params, data=data, files=files,
                                                                  timeout=120, verify=False)
        except requests.exceptions.ConnectionError as e:
            logger.log(self.name + u': Unable to connect ' + ex(e), logger.ERROR)
            return False
        except (requests.exceptions.MissingSchema, requests.exceptions.InvalidURL):
            logger.log(self.name + u': Invalid Host', logger.ERROR)
            return False
        except requests.exceptions.HTTPError as e:
            logger.log(self.name + u': Invalid HTTP Request ' + ex(e), logger.ERROR)
            return False
        except requests.exceptions.Timeout as e:
            logger.log(self.name + u': Connection Timeout ' + ex(e), logger.ERROR)
            return False
        except Exception as e:
            logger.log(self.name + u': Unknown exception raised when sending torrent to ' + self.name + ': ' + ex(e),
                       logger.ERROR)
            return False

        if response.status_code == 401:
            logger.log(self.name + u': Invalid Username or Password, check your config', logger.ERROR)
            return False

        if response.status_code in http_error_code.keys():
            logger.log(self.name + u': ' + http_error_code[response.status_code], logger.DEBUG)
            return False

        logger.log(self.name + u': Response to ' + method.upper() + ' request is ' + response.text, logger.DEBUG)

        return response

    def __request(self, func_name, func_args, func_kwargs):
        """The remote-method-call execution function.

        :param func_name: name of the method that should be executed
        :param func_args: arguments for the remote-method
        :param func_kwargs: keyword arguments for the remote-method
        :type func_name: string
        :type func_args: list of parameters
        :rtype: result of the method
        """
        self._corr_id = str(uuid.uuid4())
        request = pr.RpcRequest(func_name, func_args, func_kwargs)
        LOG.debug("Publish request: {0}".format(request))

        # publish request
        with kombu.producers[self._conn].acquire(block=True) as producer:
            exchange = self._make_exchange(
                'server_{0}_ex'.format(self._server_id),
                durable=self._durable,
                auto_delete=self._auto_delete)
            queue = self._make_queue(
                'server_{0}_queue'.format(self._server_id), exchange,
                durable=self._durable,
                auto_delete=self._auto_delete)
            producer.publish(body=request,
                             serializer='pickle',
                             exchange=exchange,
                             reply_to=self._exchange_name,
                             correlation_id=self._corr_id,
                             declare=[queue])

        # start waiting for the response
        self._wait_for_result()
        self._is_received = False

        # handler response
        result = self._response.result
        LOG.debug("Result: {!r}".format(result))
        if self._response.is_exception:
            raise result
        return result

    def _request(self, method, url, body=None, extra_hdrs={}):
        
        self._lock.acquire()
        try:
            # add the authorization header
            extraHeaders = copy(extra_hdrs)
            if self.__authorizationInfo:

                # update (digest) authorization data
                if hasattr(self.__authorizationInfo, "update"):
                    self.__authorizationInfo.update(method=method, uri=url)
                
                extraHeaders["AUTHORIZATION"] = self.__authorizationInfo.authorization
            
            # encode message parts
            body = _toUtf8(body)
            url = _urlEncode(url)
            for key, value in extraHeaders.items():
                extraHeaders[key] = _toUtf8(value)
                if key == "Destination": # copy/move header
                    if self.isConnectedToCatacomb:
                        extraHeaders[key] = _toUtf8(value.replace(Constants.SHARP, Constants.QUOTED_SHARP))
                        
                    else: # in case of TAMINO 4.4
                        extraHeaders[key] = _urlEncode(value)
            # pass message to httplib class
            for retry in range(0, Connection.MaxRetries):    # retry loop
                try:
                    self.logger.debug("REQUEST Send %s for %s" % (method, url))
                    self.logger.debug("REQUEST Body: " + repr(body))
                    for hdr in extraHeaders.items():
                        self.logger.debug("REQUEST Header: " + repr(hdr))
                    self.request(method, url, body, extraHeaders)
                    response = self.getresponse()
                    break  # no retry needed
                except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady, IncompleteRead):
                    # Workaround, start: reconnect and retry...
                    self.logger.debug("Exception occurred! Retry... ", exc_info=True)
                    self.close()
                    try:
                        self.connect()
                    except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady, IncompleteRead):
                        self.logger.debug("Connection failed.", exc_info=True)
                        raise WebdavError("Cannot perform request. Connection failed.")
                    if retry == Connection.MaxRetries - 1:
                        raise WebdavError("Cannot perform request.")
            return self.__evaluateResponse(method, response)
        finally:
            self._lock.release()

    def _request(self, function, params):
        """General-purpose function to create web requests to SHODAN.

        Arguments:
        function  -- name of the function you want to execute
        params      -- dictionary of parameters for the function

        Returns
        A JSON string containing the function's results.

        """
        # Add the API key parameter automatically
        params['key'] = self.api_key

        # Send the request
        data = urlopen(
            self.base_url +
            function +
            '?' +
            urlencode(
                params)).read(
        )

        # Parse the text into JSON
        data = loads(data)

        # Raise an exception if an error occurred
        if data.get('error', None):
            raise WebAPIError(data['error'])

        # Return the data
        return data

    def _request(self, cmd, request, response, path, **kwargs):
        if self.uuid in request['headers'].get('X-LOOP-CUSTODIA', ''):
            raise HTTPError(502, "Loop detected")
        reply = cmd(path, **kwargs)
        self._response(reply, response)

    def _request(self, method, action, params, retry_count=0, **kwargs):
        if retry_count > 6:
            raise acos_errors.ACOSUnknownError()

        try:
            return self.client.http.request(method, self.url(action), params,
                                            **kwargs)
        except acos_errors.MemoryFault as e:
            if retry_count < 5:
                time.sleep(0.1)
                return self._request(method, action, params, retry_count+1,
                                     **kwargs)
            raise e
        except acos_errors.InvalidSessionID as e:
            if retry_count < 5:
                time.sleep(0.1)
                try:
                    p = self.client.current_partition
                    self.client.session.close()
                    self.client.partition.active(p)
                except Exception:
                    pass
                return self._request(method, action, params, retry_count+1,
                                     **kwargs)
            raise e

def __request(method, url, params={}, headers={}, auth=None, callback=None):

    # Encode URL
    url_parts = url.split("\\?")
    url = url_parts[0].replace(" ", "%20")
    if len(url_parts) == 2:
        url += "?" + url_parts[1]

    # Lowercase header keys
    headers = dict((k.lower(), v) for k, v in headers.iteritems())
    headers["user-agent"] = USER_AGENT

    data, post_headers = utils.urlencode(params)
    if post_headers is not None:
        headers = dict(headers.items() + post_headers.items())

    headers['Accept-encoding'] = 'gzip'

    if auth is not None:
        if len(auth) == 2:
            user = auth[0]
            password = auth[1]
            encoded_string = base64.b64encode(user + ':' + password)
            headers['Authorization'] = "Basic " + encoded_string

    headers = dict(headers.items() + _defaultheaders.items())

    _unirestResponse = None
    if _httplib == "urlfetch":
        res = urlfetch.fetch(url, payload=data, headers=headers, method=method, deadline=_timeout)
        _unirestResponse = UnirestResponse(res.status_code,
                                           res.headers,
                                           res.content)
    else:
        req = urllib2.Request(url, data, headers)
        req.get_method = lambda: method

        try:
            response = urllib2.urlopen(req, timeout=_timeout)
            _unirestResponse = UnirestResponse(response.code, response.headers, response.read())
        except urllib2.HTTPError, e:
            response = e
            _unirestResponse = UnirestResponse(response.code, response.headers, response.read())
        except urllib2.URLError, e:
            _unirestResponse = UnirestResponse(0, {}, str(e.reason))

    if callback is None or callback == {}:
        return _unirestResponse
    else:
        callback(_unirestResponse)

    def __request(self, methodname, params):
        return ServerProxy._ServerProxy__request(self, methodname, params)

    def _request(self, method='get', params=None, data=None, files=None, cookies=None):  # pylint: disable=too-many-arguments, too-many-return-statements
        """
        Makes the actual request for the client, for everything except auth
        """

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        log_string = '{0}: Requested a {1} connection to url {2}'.format(
            self.name, method.upper(), self.url)

        if params:
            log_string += '?{0}'.format(urlencode(params))

        if data:
            log_string += ' and data: {0}{1}'.format(
                str(data)[0:99], '...' if len(str(data)) > 100 else '')

        logger.log(log_string, logger.DEBUG)

        if not self.auth:
            logger.log('{0}: Authentication Failed'.format(self.name), logger.WARNING)
            return False

        try:
            self.response = self.session.request(
                method.upper(), self.url, params=params, data=data,
                files=files, cookies=cookies, timeout=120, verify=False)

            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        logger.log('{0}: Response to the {1} request is {2}'.format
                   (self.name, method.upper(), self.response.text), logger.DEBUG)

        return True

    def _request(self, url, post=False, data=None, files=None):
        last_retry = len(settings.EXERCISE_HTTP_RETRIES) - 1
        n = 0
        while n <= last_retry:
            try:
                if post:
                    response = requests.post(url, data=data, files=files,
                        timeout=settings.EXERCISE_HTTP_TIMEOUT)
                else:
                    response = requests.get(url,
                        timeout=settings.EXERCISE_HTTP_TIMEOUT)
                if response.status_code == 200:
                    return response
                elif response.status_code >= 500 and n < last_retry:
                    logger.warning("Retrying: Server error {:d} at {}".format(
                        response.status_code, url))
                else:
                    response.raise_for_status()
            except requests.exceptions.ConnectionError as e:
                if n >= last_retry:
                    raise e
                logger.warning("Retrying: ConnectionError to {}".format(url));
            time.sleep(settings.EXERCISE_HTTP_RETRIES[n])
            n += 1
        logger.error("HTTP request loop ended in unexpected state")
        assert False

    def _request(self, msg, codec=None):
        if isinstance(msg, Msg):
            msg_code = msg.msg_code
            data = msg.data
            expect = msg.resp_code
        else:
            raise ValueError('expected a Msg argument')

        if not isinstance(codec, Codec):
            raise ValueError('expected a Codec argument')

        resp_code, data = self._send_recv(msg_code, data)
        # NB: decodes errors with msg code 0
        codec.maybe_riak_error(resp_code, data)
        codec.maybe_incorrect_code(resp_code, expect)
        if resp_code == MSG_CODE_TS_TTB_MSG or \
           resp_code in riak.pb.messages.MESSAGE_CLASSES:
            msg = codec.parse_msg(resp_code, data)
        else:
            raise Exception("unknown msg code %s" % resp_code)
        return resp_code, msg

    def _request(self, url, method):
        scheme, host = urlparse(url)[:2]
        scheme = scheme.lower()
        proxies = getproxies_environment()
        if scheme in proxies:
            scheme, host = urlparse(proxies[scheme])[:2]
            scheme = scheme.lower()

        kwargs = {}
        if version_info[1] >= 6:
            kwargs['timeout'] = self.timeout
        else:
            socket.setdefaulttimeout(self.timeout)

        if scheme == "https":
            conn = HTTPSConnection(host, **kwargs)
        else:
            conn = HTTPConnection(host, **kwargs)

        headers={}
        if method == 'GET':
            headers['Range'] = 'bytes=0-%s' % self.max_size

        try:
            try:
                conn.request(method.upper(), iri_to_uri(url),
                             headers=headers)
                response = conn.getresponse()
                data = response.read(self.max_size)
                conn.close()
            except socket.error, e:
                raise HTTPException(e.message or e.args[1])
        finally:
            if version_info[1] < 6:
                socket.setdefaulttimeout(None)

        contenttype = response.getheader('Content-Type', None)
        if contenttype:
            match = re.search('^charset=([a-zA-Z0-9-]+)', contenttype)
            try:
                if match:
                    data = data.decode(match.group(1))
                elif contenttype.startswith('text/'):
                    data = data.decode('utf-8')
            except UnicodeDecodeError:
                guessed = detect(data)
                if guessed['confidence'] > 0.5:
                    charset = guessed['encoding']
                    # Common guessing mistake:
                    if charset.startswith('ISO-8859') and '\x92' in data:
                        charset = 'windows-1252'
                    data = unicode(data, charset, errors='replace')

        return response.status, response.reason, data, response.getheaders()

    def _request(self, method, url_or_endpoint, **kwargs):
        if not url_or_endpoint.startswith(('http://', 'https://')):
            api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL)
            url = '{base}{endpoint}'.format(
                base=api_base_url,
                endpoint=url_or_endpoint
            )
        else:
            url = url_or_endpoint

        # 群发消息上传视频接口地址 HTTPS 证书错误,暂时忽略证书验证
        if url.startswith('https://file.api.weixin.qq.com'):
            kwargs['verify'] = False

        if 'params' not in kwargs:
            kwargs['params'] = {}
        if isinstance(kwargs['params'], dict) and \
                'access_token' not in kwargs['params']:
            kwargs['params']['access_token'] = self.access_token
        if isinstance(kwargs.get('data', ''), dict):
            body = json.dumps(kwargs['data'], ensure_ascii=False)
            body = body.encode('utf-8')
            kwargs['data'] = body

        kwargs['timeout'] = kwargs.get('timeout', self.timeout)
        result_processor = kwargs.pop('result_processor', None)
        res = requests.request(
            method=method,
            url=url,
            **kwargs
        )
        try:
            res.raise_for_status()
        except requests.RequestException as reqe:
            raise WeChatClientException(
                errcode=None,
                errmsg=None,
                client=self,
                request=reqe.request,
                response=reqe.response
            )

        return self._handle_result(
            res, method, url, result_processor, **kwargs
        )

    def _request(self, method, url, body=None, extra_hdrs={}):

        self._lock.acquire()
        try:
            # add the authorization header
            extraHeaders = copy(extra_hdrs)
            if self.__authorizationInfo:

                # update (digest) authorization data
                if hasattr(self.__authorizationInfo, "update"):
                    self.__authorizationInfo.update(method=method, uri=url)

                extraHeaders["AUTHORIZATION"] = self.__authorizationInfo.authorization

            # encode message parts
            body = _toUtf8(body)
            url = _urlEncode(url)
            for key, value in extraHeaders.items():
                extraHeaders[key] = _toUtf8(value)
                if key == "Destination": # copy/move header
                    if self.isConnectedToCatacomb:
                        extraHeaders[key] = _toUtf8(value.replace(Constants.SHARP, Constants.QUOTED_SHARP))

                    else: # in case of TAMINO 4.4
                        extraHeaders[key] = _urlEncode(value)
            # pass message to httplib class
            for retry in range(0, Connection.MaxRetries):    # retry loop
                try:
                    self.logger.debug("REQUEST Send %s for %s" % (method, url))
                    self.logger.debug("REQUEST Body: " + repr(body))
                    for hdr in extraHeaders.items():
                        self.logger.debug("REQUEST Header: " + repr(hdr))
                    self.request(method, url, body, extraHeaders)
                    response = self.getresponse()
                    break  # no retry needed
                except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady, IncompleteRead):
                    # Workaround, start: reconnect and retry...
                    self.logger.debug("Exception occurred! Retry... ", exc_info=True)
                    self.close()
                    try:
                        self.connect()
                    except (CannotSendRequest, socket.error, BadStatusLine, ResponseNotReady, IncompleteRead):
                        self.logger.debug("Connection failed.", exc_info=True)
                        raise WebdavError("Cannot perform request. Connection failed.")
                    if retry == Connection.MaxRetries - 1:
                        raise WebdavError("Cannot perform request.")
            return self.__evaluateResponse(method, response)
        finally:
            self._lock.release()

    def _request(self, method, arguments=None, ids=None, require_ids=False, timeout=None):
        """
        Send json-rpc request to Transmission using http POST
        """
        if not isinstance(method, string_types):
            raise ValueError('request takes method as string')
        if arguments is None:
            arguments = {}
        if not isinstance(arguments, dict):
            raise ValueError('request takes arguments as dict')
        ids = parse_torrent_ids(ids)
        if len(ids) > 0:
            arguments['ids'] = ids
        elif require_ids:
            raise ValueError('request require ids')

        query = json.dumps({'tag': self._sequence, 'method': method, 'arguments': arguments})
        self._sequence += 1
        start = time.time()
        http_data = self._http_query(query, timeout)
        elapsed = time.time() - start
        LOGGER.info('http request took {time:.3f} s'.format(time=elapsed))

        try:
            data = json.loads(http_data)
        except ValueError as error:
            LOGGER.error('Error: {msg}'.format(msg=error))
            LOGGER.error('Request: {request!r}'.format(request=query))
            LOGGER.error('HTTP data: {data!r}'.format(data=http_data))
            raise

        LOGGER.debug(json.dumps(data, indent=2))
        if 'result' in data:
            if data['result'] != 'success':
                raise TransmissionError('Query failed with result {result!r}.'.format(result=data['result']))
        else:
            raise TransmissionError('Query failed without result.')

        results = {}
        if method == 'torrent-get':
            for item in data['arguments']['torrents']:
                results[item['id']] = Torrent(self, item)
                if self.protocol_version == 2 and 'peers' not in item:
                    self.protocol_version = 1
        elif method == 'torrent-add':
            item = None
            if 'torrent-added' in data['arguments']:
                item = data['arguments']['torrent-added']
            elif 'torrent-duplicate' in data['arguments']:
                item = data['arguments']['torrent-duplicate']
            if item:
                results[item['id']] = Torrent(self, item)
            else:
                raise TransmissionError('Invalid torrent-add response.')
        elif method == 'session-get':
            self._update_session(data['arguments'])
        elif method == 'session-stats':
            # older versions of T has the return data in "session-stats"
            if 'session-stats' in data['arguments']:
                self._update_session(data['arguments']['session-stats'])
            else:
                self._update_session(data['arguments'])
        elif method in ('port-test', 'blocklist-update', 'free-space', 'torrent-rename-path'):
            results = data['arguments']
        else:
            return None

        return results

    def _request(self, method, url, **kwargs):
        """
        Low level request helper that actually executes the request towards a
        wanted URL.

        This does NOT do any authentication.
        """
        # NOTE: Allow passing the url as just the path or a full url
        if not url.startswith('http'):
            if not url.startswith('/REST'):
                url = '/REST' + url
            url = self.endpoint + url

        kwargs.setdefault("headers", kwargs.get("headers", {}))
        kwargs['proxies'] = utils.get_proxies()

        if self.token is not None:
            kwargs['headers']['Auth-Token'] = self.token
        if self.timeout is not None:
            kwargs.setdefault("timeout", self.timeout)

        data = kwargs.get('data')
        if data is not None:
            kwargs['data'] = data.copy()

            # NOTE: We don't want to log the credentials (password) that are
            # used in a auth request.
            if 'password' in kwargs['data']:
                kwargs['data']['password'] = '**SECRET**'

            self._http_log_req(method, url, kwargs)

            # NOTE: Set it back to the original data and serialize it.
            kwargs['data'] = json.dumps(data)
        else:
            self._http_log_req(method, url, kwargs)

        if self.timings:
            start_time = time.time()
        resp = self.http.request(method, url, **kwargs)
        if self.timings:
            self.times.append(("%s %s" % (method, url),
                               start_time, time.time()))
        self._http_log_resp(resp)

        if resp.status_code >= 400:
            LOG.debug(
                "Request returned failure status: %s" %
                resp.status_code)
            raise DynClientError.from_response(resp)
        return resp

    def __request__(self, handler, *args):
        return _get_conn(self).sync_request(handler, _get_oid(self), *args)

    def _request(self, method, url, **kwargs):
        """Perform REST request and save response info."""
        try:
            LOG.debug("%(method)s: Request for %(resource)s payload: "
                      "%(payload)s",
                      {'method': method.upper(), 'resource': url,
                       'payload': kwargs.get('data')})
            start_time = time.time()
            response = self.session.request(method, url, verify=False,
                                            timeout=self.timeout, **kwargs)
            LOG.debug("%(method)s Took %(time).2f seconds to process",
                      {'method': method.upper(),
                       'time': time.time() - start_time})
        except (r_exc.Timeout, r_exc.SSLError) as te:
            # Should never see SSLError, unless requests package is old (<2.0)
            timeout_val = 0.0 if self.timeout is None else self.timeout
            LOG.warning(_LW("%(method)s: Request timeout%(ssl)s "
                            "(%(timeout).3f sec) for CSR(%(host)s)"),
                        {'method': method,
                         'timeout': timeout_val,
                         'ssl': '(SSLError)'
                         if isinstance(te, r_exc.SSLError) else '',
                         'host': self.host})
            self.status = requests.codes.REQUEST_TIMEOUT
        except r_exc.ConnectionError:
            LOG.exception(_LE("%(method)s: Unable to connect to "
                              "CSR(%(host)s)"),
                          {'method': method, 'host': self.host})
            self.status = requests.codes.NOT_FOUND
        except Exception as e:
            LOG.error(_LE("%(method)s: Unexpected error for CSR (%(host)s): "
                          "%(error)s"),
                      {'method': method, 'host': self.host, 'error': e})
            self.status = requests.codes.INTERNAL_SERVER_ERROR
        else:
            self.status = response.status_code
            LOG.debug("%(method)s: Completed [%(status)s]",
                      {'method': method, 'status': self.status})
            return self._response_info_for(response, method)

    def _request(self, method, path, server=None, **kwargs):
        """Execute a request to the cluster

        A server is selected from the server pool.
        """
        while True:
            next_server = server or self._get_server()
            try:
                response = self.server_pool[next_server].request(
                    method, path, **kwargs)
                redirect_location = response.get_redirect_location()
                if redirect_location and 300 <= response.status <= 308:
                    redirect_server = _server_url(redirect_location)
                    self._add_server(redirect_server)
                    return self._request(
                        method, path, server=redirect_server, **kwargs)
                if not server and response.status in SRV_UNAVAILABLE_STATUSES:
                    with self._lock:
                        # drop server from active ones
                        self._drop_server(next_server, response.reason)
                else:
                    return response
            except (urllib3.exceptions.MaxRetryError,
                    urllib3.exceptions.ReadTimeoutError,
                    urllib3.exceptions.SSLError,
                    urllib3.exceptions.HTTPError,
                    urllib3.exceptions.ProxyError,) as ex:
                ex_message = _ex_to_message(ex)
                if server:
                    raise ConnectionError(
                        "Server not available, exception: %s" % ex_message
                    )
                with self._lock:
                    # drop server from active ones
                    self._drop_server(next_server, ex_message)
            except Exception as e:
                raise ProgrammingError(_ex_to_message(e))

    def _request(self, uri, params, resp_reader):
        post_data = dict(params) 
        post_data["api_key"] = self._api_key
        post_data["v"] = self._version
        post_data["format"] = "xml"
        post_data["sig"] = hashlib.md5(self._api_key + self._secret + str(int(time.time())))
        
        try:
            r = urllib2.urlopen(self._url + uri, urlencode(post_data))
        except urllib2.URLError, e:
            if isinstance(e, urllib2.HTTPError):
                resp_body = e.read() if e.fp is not None else ""
                raise GoGridError("Request failed. %s. URL: %s. Service message: %s" % (e, self.url, resp_body))
            else:
                raise GoGridError("Cannot connect to GoGrid service. %s" % (e,))
        else:
            try:
                xml = parseString(r.read())
            except (Exception, BaseException), e:
                raise GoGridError("Response couldn't be parsed as XML. %s" % (e,))
            else:
                return resp_reader(xml_strip(xml))

    def __request(self, methodname, params):
        self.__id += 1
        id_ = self.__id
        request = json.dumps({
                'id': id_,
                'method': methodname,
                'params': params,
                }, cls=JSONEncoder)

        try:
            response = self.__transport.request(
                self.__host,
                self.__handler,
                request,
                verbose=self.__verbose
                )
        except (socket.error, httplib.HTTPException), v:
            if (isinstance(v, socket.error)
                    and v.args[0] == errno.EPIPE):
                raise
            # try one more time
            self.__transport.close()
            response = self.__transport.request(
                self.__host,
                self.__handler,
                request,
                verbose=self.__verbose
                )
        except xmlrpclib.ProtocolError, e:
            raise Fault(str(e.errcode), e.errmsg)
        except:
            self.__transport.close()
            raise

        if response['id'] != id_:
            raise ResponseError('Invalid response id (%s) excpected %s' %
                (response['id'], id_))
        if response.get('error'):
            raise Fault(*response['error'])
        return response['result']

    def _request(self, url, method, **kwargs):
        if self.timeout is not None:
            kwargs.setdefault('timeout', self.timeout)

        kwargs.setdefault('headers', kwargs.get('headers', {}))
        kwargs['headers']['User-Agent'] = self.user_agent

        try:
            if kwargs['body'] is 'json':
                kwargs['headers']['Accept'] = 'application/json'
                kwargs['headers']['Content-Type'] = 'application/json'
            elif kwargs['body'] is 'xml':
                kwargs['headers']['Accept'] = 'application/xml'
                kwargs['headers']['Content-Type'] = 'application/xml'
            elif kwargs['body'] is 'text':
                kwargs['headers']['Accept'] = 'text/plain'
                kwargs['headers']['Content-Type'] = 'text/plain'
            elif kwargs['body'] is 'binary':
                kwargs['headers']['Accept'] = 'application/octet-stream'
                kwargs['headers']['Content-Type'] = 'application/octet-stream'
            else:
                raise exceptions.UnsupportedRequestType()
        except KeyError:
            # Default if body type is unspecified is text/plain
            kwargs['headers']['Accept'] = 'text/plain'
            kwargs['headers']['Content-Type'] = 'text/plain'

        # Optionally verify if requested body type is supported
        try:
            if kwargs['body'] not in kwargs['supported_body_types']:
                raise exceptions.UnsupportedBodyType()
            else:
                del kwargs['supported_body_types']
        except KeyError:
            pass

        del kwargs['body']

        self.log.debug("{0} URL: {1}{2} - {3}"
                       .format(method, self.endpoint, url, str(kwargs)))

        resp = self.http.request(
            method,
            self.endpoint + url,
            **kwargs)

        if resp.text:
            try:
                if kwargs['headers']['Content-Type'] is 'application/json':
                    body = json.loads(resp.text)
                elif kwargs['headers']['Content-Type'] is 'application/xml':
                    body = etree.XML(resp.text)
                else:
                    body = resp.text
            except ValueError:
                body = None
        else:
            body = None

        return resp, body

    def __request__(self, handler, *args):
        res = AsyncResult(_get_conn(self))
        _get_conn(self).async_request(res.callback, handler, _get_oid(self), *args)
        return res

    @_request.setter
    def _request(self, value):
        if value is not None and not isinstance(value, weakref.ProxyType):
            value = weakref.proxy(value)
        self.__request = value

    def __request__(self, req_type, url, username=None, password=None, value=None):
        lurl = url.split('/')
        # extract HOST http(s)://HOST/path/...
        host = lurl[2]
        # rebuild path from parts
        purl = '/' + '/'.join(lurl[3:])
        # select protocol: http or https
        if url.startswith('https'):
            conn = http.client.HTTPSConnection(host, timeout=self.timeout)
        else:
            conn = http.client.HTTPConnection(host, timeout=self.timeout)
        # add headers
        hdrs = {'Accept': 'text/plain'}
        if username and password:
            hdrs['Authorization'] = 'Basic ' + base64.b64encode(username + ':' + password)

        if 'POST' == req_type:
            data = urllib.parse.urlencode({'value': value})
            data = data.encode('utf-8')
            request = urllib.request.Request(url)
            # adding charset parameter to the Content-Type header.
            request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
            f = urllib.request.urlopen(request, data)
            if f.status in (http.client.OK, http.client.CREATED):
                return f.read().decode('utf-8')
                self.logger.warning("request failed: {0}: ".format(url))
                # self.logger.debug("{0} response: {1} {2}".format(req_type, f.status, f.reason))
            return None
        elif 'PUT' == req_type:
            conn.request(req_type, purl, body=value, headers=hdrs)
        else:  # 'GET' or 'DELETE'
            conn.request(req_type, purl, headers=hdrs)
        resp = conn.getresponse()
        conn.close()
        # success status: 201/Created for PUT request, else 200/Ok
        if resp.status in (http.client.OK, http.client.CREATED):
            return resp.read()
        self.logger.warning("request failed for: {0}: ".format(url))
        # self.logger.debug("{0} response: {1} {2}".format(req_type, resp.status, resp.reason))
        return None

    def __request (self, methodname, params):
        method_function = ServerProxy.__getattr__(self,methodname)
        self.__params = dict()
        if params and type(params) is tuple and len(params)>0 and type(params[0]) is dict:
            self.__params.update(params[0])

        try:
            response = method_function(self.__params)
        except Fault, err:
            raise NameError("Fault", err)
        except ProtocolError, err:
            raise NameError("ProtocolError", err)
        except Exception, err:
            raise NameError("Some other error occured, presumably with the network connection to %s" % self.__address, err)
        if response['code'] < 2000:
            try:
                return response['resData']
            except:
                # not all requests send a response
                return None
        else:
            raise NameError('There was a problem: %s (Error code %s)' % (response['msg'], response['code']), response)

    def _request(self, method, path, queries=(), body=None, ensure_encoding=True,
                 log_request_body=True, ignore_prefix=False):
        """
        make a HTTP request to the pulp server and return the response

        :param method:  name of an HTTP method such as GET, POST, PUT, HEAD
                        or DELETE
        :type  method:  basestring

        :param path:    URL for this request
        :type  path:    basestring

        :param queries: mapping object or a sequence of 2-element tuples,
                        in either case representing key-value pairs to be used
                        as query parameters on the URL.
        :type  queries: mapping object or sequence of 2-element tuples

        :param body:    Data structure that will be JSON serialized and send as
                        the request's body.
        :type  body:    Anything that is JSON-serializable.

        :param ensure_encoding: toggle proper string encoding for the body
        :type ensure_encoding: bool

        :param log_request_body: Toggle logging of the request body, defaults to true
        :type log_request_body: bool

        :param ignore_prefix: when building the url, disregard the self.path_prefix
        :type  ignore_prefix: bool

        :return:    Response object
        :rtype:     pulp.bindings.responses.Response

        :raises:    ConnectionException or one of the RequestExceptions
                    (depending on response codes) in case of unsuccessful
                    request
        """
        url = self._build_url(path, queries, ignore_prefix)
        if ensure_encoding:
            body = self._process_body(body)
        if not isinstance(body, (NoneType, basestring)):
            body = json.dumps(body)
        self.log.debug('sending %s request to %s' % (method, url))

        response_code, response_body = self.server_wrapper.request(method, url, body)

        if self.api_responses_logger:
            if log_request_body:
                self.api_responses_logger.info(
                    '%s request to %s with parameters %s' % (method, url, body))
            else:
                self.api_responses_logger.info(
                    '%s request to %s' % (method, url))
            self.api_responses_logger.info("Response status : %s \n" % response_code)
            self.api_responses_logger.info(
                "Response body :\n %s\n" % json.dumps(response_body, indent=2))

        if response_code >= 300:
            self._handle_exceptions(response_code, response_body)
        elif response_code == 200 or response_code == 201:
            body = response_body
        elif response_code == 202:
            if isinstance(response_body, list):
                body = [Task(t) for t in response_body]
            else:
                body = Task(response_body)

        return Response(response_code, body)

    def __request(self, method, endpoint, data):
        """ Do requests """
        url = self.__get_url(endpoint)
        auth = None
        params = {}
        headers = {
            "user-agent": "WooCommerce API Client-Python/%s" % __version__,
            "content-type": "application/json;charset=utf-8",
            "accept": "application/json"
        }

        if self.is_ssl is True and self.query_string_auth is False:
            auth = (self.consumer_key, self.consumer_secret)
        elif self.is_ssl is True and self.query_string_auth is True:
            params = {
                "consumer_key": self.consumer_key,
                "consumer_secret": self.consumer_secret
            }
        else:
            url = self.__get_oauth_url(url, method)

        if data is not None:
            data = jsonencode(data, ensure_ascii=False).encode('utf-8')

        return request(
            method=method,
            url=url,
            verify=self.verify_ssl,
            auth=auth,
            params=params,
            data=data,
            timeout=self.timeout,
            headers=headers
        )

    def __request(self, name, args):
        payload = {'method': unicode(name), 'params': args, 'id': 0}
        version = args[1].get('version', VERSION_WITHOUT_CAPABILITIES)
        payload = json_encode_binary(payload, version)

        if self.__verbose >= 2:
            root_logger.info('Request: %s',
                             json.dumps(payload, sort_keys=True, indent=4))

        response = self.__transport.request(
            self.__host,
            self.__handler,
            json.dumps(payload).encode('utf-8'),
            verbose=self.__verbose >= 3,
        )

        try:
            response = json_decode_binary(json.loads(response.decode('ascii')))
        except ValueError as e:
            raise JSONError(error=str(e))

        if self.__verbose >= 2:
            root_logger.info(
                'Response: %s',
                json.dumps(json_encode_binary(response, version),
                           sort_keys=True, indent=4)
            )
        error = response.get('error')
        if error:
            try:
                error_class = errors_by_code[error['code']]
            except KeyError:
                raise UnknownError(
                    code=error.get('code'),
                    error=error.get('message'),
                    server=self.__host,
                )
            else:
                kw = error.get('data', {})
                kw['message'] = error['message']
                raise error_class(**kw)

        return response['result']