如何在python中的POST请求中发送urlencoded参数

时间:2017-07-07 07:04:27

标签: python api heroku flask urlencode

我正在尝试将生产就绪代码部署到Heroku来测试它。不幸的是,它没有采用JSON数据,因此我们转换为x-www-form-urlencoded。

params = urllib.parse.quote_plus(json.dumps({
    'grant_type': 'X',
    'username': 'Y',
    'password': 'Z'
}))
r = requests.post(URL, data=params)
print(params)

这行显示错误,因为我猜data=params的格式不正确。

有没有办法将urlencoded参数发布到API?

3 个答案:

答案 0 :(得分:4)

您不需要显式编码,只需传递一个字典。

>>> r = requests.post(URL, data = {'key':'value'})

来自documentation:

  

通常,您希望发送一些表单编码数据 - 非常类似于HTML   形成。为此,只需将字典传递给data参数即可。您的   数据字典将在请求时自动进行表单编码   是

答案 1 :(得分:3)

Dialog alert = Dialog( elevation: 0, backgroundColor: Colors.greenAccent, //backgroundColor: hexToColor('#f26937'), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), ), //title: Text("My title"), child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(1.0)), child:Container( margin: EdgeInsets.only(right: width-54-232,left: width-54-232), color: hexToColor('#f26937'), height: 120, width: 120, child : Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( child: CircularProgressIndicator( //backgroundColor: Colors.white, valueColor: new AlwaysStoppedAnimation<Color>(Colors.white), ), height: 54.0, width: 54.0, ) ],) ),) 标头设置为Content-Type

application/x-www-form-urlencoded

答案 2 :(得分:0)

需要注意的重要一点是,对于嵌套的json数据,您需要将嵌套的json对象转换为字符串。

data = { 'key1': 'value',
         'key2': {
                'nested_key1': 'nested_value1',
                'nested_key2': 123
         }

       }

字典需要以这种格式转换

inner_dictionary = {
                'nested_key1': 'nested_value1',
                'nested_key2': 123
         }


data = { 'key1': 'value',
         'key2': json.dumps(inner_dictionary)

       }

r = requests.post(URL, data = data)