简体   繁体   English

请求POST中的URL编码字符串

[英]URL encoded string in Requests POST

I'm sure this is really banal and stupid but I cannot figure it out for the life of me. 我确信这确实是平庸而愚蠢的,但我无法终生解决。

I'm working with the Alchemy API, where the POST request using Requests looks like 我正在使用Alchemy API,其中使用Requests的POST请求看起来像

r = requests.post(url, payload, headers=headers)

where payload is a dict with a field for url-encoded text like text=this%20is%text 有效负载是字典,其中包含用于URL编码的文本(例如text=this%20is%text的字段

The stupid problem I'm having is that if I use urllib for the encoding like myText = urlencode({'text': textToEncode}) 我遇到的愚蠢问题是,如果我使用urllib进行myText = urlencode({'text': textToEncode})这样的编码

I can't then insert it into the payload where payload={'text': myText} because then I get something probably like text=text=this%20is%text 然后,我无法将其插入有效payload={'text': myText}的有效负载中,因为这样我可能会得到类似于text=text=this%20is%text

This would be so much simpler if I could just encode the string itself. 如果我可以对字符串本身进行编码,这将非常简单。 The encoding function adds this stuff I can't turn around an insert into the dict because the whole dict gets encoded. 编码功能将这些内容添加到了我无法绕开字典的插入中,因为整个字典都已编码。

Am I missing something incredibly simple and dumb? 我是否错过了令人难以置信的简单愚蠢的东西?

Try including the Content-type header, for example application/json and then using data=json.dumps(payload) . 尝试包含Content-type标头,例如application/json ,然后使用data=json.dumps(payload)

import json
headers['Content-type'] = 'application/json'
r = requests.post(url, data=json.dumps(payload), headers=headers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM