Circular issue: Attempt to send form-url-encoded data causes TypeError: can't concat bytes to str, and the fix to latter breaks the former
Circular issue: Attempt to send form-url-encoded data causes TypeError: can't concat bytes to str, and the fix to latter breaks the former
当我试着按照这个问题的答案去做时Python requests module sends JSON string instead of x-www-form-urlencoded param string and pass a dict to the urlopen, I get the error described in this question:
代码基于第一个问题答案中的推荐:
req = Request(url, method='POST', data={"ID": theId})
r = urlopen(req)
当我尝试应用第二个问题的已接受答案并使用它(类似于我的原始代码)时...
urllib.request.urlopen({api_url}, data=bytes(json.dumps({"ID": theId}), encoding="utf-8"))
...我又回到了第一个问题开始的地方,因为在 data
参数中传递 json 字符串会强制发送 application/json
而不是我正在寻找的x-www-form-urlencoded
:
有没有办法跳出这个循环陷阱?
已通过调用 urllib.parse.urlencode
将 dict 转换为字符串,然后显式设置内容类型来修复:
postparam = urllib.parse.urlencode({"ID": theId}).encode('utf-8')
req = Request(url, method='POST', data=postparam)
req.add_header("content-type", "application/x-www-form-urlencoded")
r = urlopen(req)
当我试着按照这个问题的答案去做时Python requests module sends JSON string instead of x-www-form-urlencoded param string and pass a dict to the urlopen, I get the error described in this question:
代码基于第一个问题答案中的推荐:
req = Request(url, method='POST', data={"ID": theId})
r = urlopen(req)
当我尝试应用第二个问题的已接受答案并使用它(类似于我的原始代码)时...
urllib.request.urlopen({api_url}, data=bytes(json.dumps({"ID": theId}), encoding="utf-8"))
...我又回到了第一个问题开始的地方,因为在 data
参数中传递 json 字符串会强制发送 application/json
而不是我正在寻找的x-www-form-urlencoded
:
有没有办法跳出这个循环陷阱?
已通过调用 urllib.parse.urlencode
将 dict 转换为字符串,然后显式设置内容类型来修复:
postparam = urllib.parse.urlencode({"ID": theId}).encode('utf-8')
req = Request(url, method='POST', data=postparam)
req.add_header("content-type", "application/x-www-form-urlencoded")
r = urlopen(req)