convert origin dict to x-www-form-urlencoded

    Args:
        post_data (dict):
            {"a": 1, "b":2}

    Returns:
        str:
            a=1&b=2
970412
def x_www_form_urlencoded(post_data):
    
    if isinstance(post_data, dict):
        return "&".join([
            u"{}={}".format(key, value)
            for key, value in post_data.items()
        ])
    else:
        return post_data
365011
def postURL(self, url, headers={}, body=None):
        
        return self._load_resource("POST", url, headers, body)
1030422
def set_form_data(params, sep = '&')
      self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
      self.content_type = 'application/x-www-form-urlencoded'
    end
1055656
function (data) {
    var str = '', start = true;
    var jsondata = '';
    for (var key in data) {
      if (typeof (jsondata = JSON.stringify(data[key])) === 'string') {
        str += (start? '': '&');
        str += encodeURIComponent(key) + '=' + encodeURIComponent(jsondata);
        if (start) { start = false; }
      }
    }
    return str;
  }
327522
def posted_data_dict(self):
        
        if not self.query:
            return None
        from django.http import QueryDict
        roughdecode = dict(item.split('=', 1) for item in self.query.split('&'))
        encoding = roughdecode.get('charset', None)
        if encoding is None:
            encoding = DEFAULT_ENCODING
        query = self.query.encode('ascii')
        data = QueryDict(query, encoding=encoding)
        return data.dict()
453418
function encode(data, parse_url) {
    var str;
    var t = typeof data;

    if (t == 'string' || t == 'number') {
        str = '' + data;
        data = new Buffer(str);
    } else if (Buffer.isBuffer(data)) {
        str = data.toString();
    } else if (Array.isArray(data)) {
        data = new Buffer(data);
        str = data.toString();
    } else {
        throw new Error("Bad data");
    }

    if (/^[0-9]+$/.test(str)) {
        if (data.length > 7089) {
            throw new Error("Too much data");
        }
        return encode_numeric(str);
    }

    if (/^[0-9A-Z \$%\*\+\.\/\:\-]+$/.test(str)) {
        if (data.length > 4296) {
            throw new Error("Too much data");
        }
        return encode_alphanum(str);
    }

    if (parse_url && /^https?:/i.test(str)) {
        return encode_url(str);
    }

    if (data.length > 2953) {
        throw new Error("Too much data");
    }
    return encode_8bit(data);
}
399732
def to_dict_str(origin_value, encode=None):
    
    value = copy.deepcopy(origin_value)
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = to_dict_str(v, encode)
            continue

        if isinstance(v, list):
            value[k] = to_list_str(v, encode)
            continue

        if encode:
            value[k] = encode(v)
        else:
            value[k] = default_encode(v)

    return value
910028
def post_parse(self, uri, params={}, data={}):
        '''
        '''
        return self._request_parse(self.post, uri, params, data)
369975
def postJSON(g, data):
    
    g.clog.debug('Entering postJSON')

    # encode data as json
    json_data = json.dumps(data).encode('utf-8')

    # Send the xml to the server
    url = urllib.parse.urljoin(g.cpars['hipercam_server'], g.SERVER_POST_PATH)
    g.clog.debug('Server URL = ' + url)

    opener = urllib.request.build_opener()
    g.clog.debug('content length = ' + str(len(json_data)))
    req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'})
    response = opener.open(req, timeout=15).read()
    g.rlog.debug('Server response: ' + response.decode())
    csr = ReadServer(response, status_msg=False)
    if not csr.ok:
        g.clog.warn('Server response was not OK')
        g.rlog.warn('postJSON response: ' + response.decode())
        g.clog.warn('Server error = ' + csr.err)
        return False

    # now try to setup nodding server if appropriate
    if g.cpars['telins_name'] == 'GTC':
        url = urllib.parse.urljoin(g.cpars['gtc_offset_server'], 'setup')
        g.clog.debug('Offset Server URL = ' + url)
        opener = urllib.request.build_opener()
        try:
            req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'})
            response = opener.open(req, timeout=5).read().decode()
        except Exception as err:
            g.clog.warn('Could not communicate with GTC offsetter')
            g.clog.warn(str(err))
            return False

        g.rlog.info('Offset Server Response: ' + response)
        if not json.loads(response)['status'] == 'OK':
            g.clog.warn('Offset Server response was not OK')
            return False

    g.clog.debug('Leaving postJSON')
    return True
666387
def safe_urlencode(params, doseq=0):
    
    if IS_PY3:
        return urlencode(params, doseq)

    if hasattr(params, "items"):
        params = params.items()

    new_params = []

    for k, v in params:
        k = k.encode("utf-8")

        if isinstance(v, (list, tuple)):
            new_params.append((k, [force_bytes(i) for i in v]))
        else:
            new_params.append((k, force_bytes(v)))

    return urlencode(new_params, doseq)
306998
def to_postdata(self):
        """"""
        items = []
        for k, v in sorted(self.items()):  # predictable for testing
            items.append((k.encode('utf-8'), to_utf8_optional_iterator(v)))

        # tell urlencode to deal with sequence values and map them correctly
        # to resulting querystring. for example self["k"] = ["v1", "v2"] will
        # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
        return urlencode(items, True).replace('+', '%20').encode('ascii')
774569
private function setPostFields(array $post_data)
    {
        $pd = [];
        foreach ($post_data as $k => $v) {
            $pd[] = "$k=$v";
        }
        $pd = implode("&", $pd);
        \Unirest\Request::curlOpt(CURLOPT_POST, true);
        \Unirest\Request::curlOpt(CURLOPT_POSTFIELDS, $pd);
        \Unirest\Request::curlOpt(CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    }
883814
def read_request_from_str(data, **params):
    
    method, uri = None, None
    headers = {}
    host = ''

    try:
        split_list = data.split('\n\n')
        headers_text = split_list[0]
        body = '\n\n'.join(split_list[1:])
    except:
        headers_text = data
        body = ''

    body = force_bytes(body)
    for k, v in params.items():
        body = body.replace(b'{%s}' % force_bytes(k), force_bytes(v))

    header_list = headers_text.split('\n')

    for i, line in enumerate(header_list):
        line = line.strip()
        if line.strip() == '':
            continue

        line = line.format(**params)
        if i == 0:
            # 至多3个
            split_line = line.strip().split(' ')
            method, uri, _ = split_line[0], ' '.join(split_line[1:-1]), split_line[-1]
        else:
            # 至多2个
            header, value = line.split(':', 1)
            header = header.strip()
            value = value.strip()
            headers[header] = value
            if header.lower() == 'host':
                host = value

    return headers, method, uri, host, body
506015
def post_data(self, url, params):
        
        url = urljoin(self.endpoint, url)
        headers = {'Authorization': self.token}
        req = requests.post(url, headers=headers, data=params, verify=False)

        if req.status_code == 204:
            return True

        if req.status_code == 404:
            raise NotFoundError()

        try:
            data = req.json()
        except ValueError as e:
            raise JSONReadError(
                'Read failed from API: %s' % str(e)
            )

        if not req.ok:
            msg = [data[m] for m in ("id", "message") if m in data][1]
            raise DataReadError(msg)

        return data
190547
def encode_data(data):
    '''
    
    '''
    if isinstance(data, (six.string_types, bytes)):
        return encode_string(data)
    elif isinstance(data, (six.integer_types, bool, float)):
        return data
    elif data is None:
        return data
    elif isinstance(data, list):
        return [encode_data(x) for x in data]
    elif isinstance(data, dict):
        return {k: encode_data(v) for k, v in data.items()}
    else:
        raise ValueError('Cannot encode data of type %s' % type(data))
225005
def post_json(self, url, data, cls=None, **kwargs):
        
        kwargs['data'] = to_json(data, cls=cls)
        kwargs['headers'] = self.default_headers
        return self.post(url, **kwargs).json()
371730
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
        ''''''
        if 'Api-Lang' not in headers:
            headers['Api-Lang'] = 'python'
        if 'Content-Type' not in headers:
            headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset
        rsp = requests.post(url, data, headers=headers,
                            timeout=(int(self.conf(HTTP_CONN_TIMEOUT, '10')), int(self.conf(HTTP_SO_TIMEOUT, '30'))))
        return json.loads(rsp.text)