【问题标题】: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循环问题:尝试发送 form-url-encoded 数据导致 TypeError: can't concat bytes to str,并且对后者的修复会破坏前者
【发布时间】:2019-02-27 04:01:01
【问题描述】:

当我尝试按照这个问题的答案 Python requests module sends JSON string instead of x-www-form-urlencoded param string 并将 dict 传递给 urlopen 时,我得到了这个问题中描述的错误:Python 3.6 urllib TypeError: can't concat bytes to str

代码基于第一个问题的答案中的推荐:

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

有没有办法摆脱这个循环陷阱?

【问题讨论】:

  • 您能否显示您的urlopen 调用的另一个版本,它给出了bytes 相关错误?
  • 已编辑问题,还找到了两个链接问题中未提及的解决方案。

标签: python python-3.x urllib


【解决方案1】:

通过调用 urllib.parse.urlencode 将 dict 转换为字符串,然后显式设置 content-type 来修复:

    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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2023-03-27
    • 2021-10-02
    相关资源
    最近更新 更多