【问题标题】:Python request module gives error 400(bad request) for POSTPython 请求模块为 POST 提供错误 400(错误请求)
【发布时间】:2017-02-06 15:04:30
【问题描述】:

我是 http 请求的新手,并试图自动化一些工作。但我无法得到所需的结果。我查看了很多关于 python 请求模块的帖子和文档,但结果没有变化。

我写的代码

def installFont():
    print "Installing font"
    urlToHit = "some http address"
    header_ = {  "UserID": "00000",  "PortalName": "EDC",  "ModifyBy" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type" : "application/json"}

    body_ = {
  "Email": "abc@xyz.com",
  "AssetLicenseType": "Trial",
  "MachineIds":  ["machine1", "machine2"],
  "fontAsset":
  [
     {
          "FontId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
          "FontName": "Neue Aachen™ Pro Ultra Light",
          "FontUrl": "http://helveticaurl",
          "FontDownloadUrlAPI": "url",
          "FontDownloadUrl" : "url1,
          "FontFamilyName": "Neue Aachen™ Pro",
          "FontFamilyUrl": "http://FontFamilyUrl",
          "FontStyle": "Normal",
          "FontWeight": "100",
          "ExpiryDate": "2017-2-27 11:17:01",
          "FontFamilyId": "34"
     }                  
  ]
}

r = requests.request("POST", urlToHit, data=body_, headers=header_)
print r.headers
print r.status_code
print r.text

用邮递员尝试了同样的事情,这给了我正确的结果,但通过 python 我得到的输出为

{'X-Processing-Time-Milliseconds': '3', 'Transfer-Encoding': 'chunked', 'X-Powered-By': 'ASP.NET', 'Server': 'Kestrel', 'Date' :'星期一,2017 年 2 月 6 日 14:51:59 GMT','Content-Type':'application/json'} 400 {“信息”:”''”}

我认为我在传递 body_ 时犯了一些错误

r = requests.request("POST", urlToHit, data=body_, headers=header_)

通过邮递员输出 {"Message":"Created Successfully","SuccessCount":2,"FailCount":0}

【问题讨论】:

  • 我进一步研究了它,我假设问题出在 fontAssest 字段上。当我从“body_”中删除此字段时,响应为 {“Message”:“'至少需要一种字体资源'”}。但是 body_ 与 POSTMAN 工具完全兼容。所以 fontAsset 是字典列表。也许我需要把注意力转移到我需要如何传递这样的帖子请求上。
  • 请不要在这个问题上浪费时间。有一个特殊字符 ™ 需要注意。我现在可以得到所需的结果。

标签: python python-requests


【解决方案1】:

你需要使用:

r = requests.post(urlToHit, json=body_, headers=headers_)

请转至documentation。

【讨论】:

  • 我已经检查过r = requests.post(urlToHit, data=body_, headers=headers_)。 'requests.post(urlToHit, data=body_, headers=headers_)' 调用'requests.request("POST", urlToHit, data=body_, headers=header_)'。
  • 我还检查了将 body_ 转换为字符串 """value of body_"""。正如其在 data = :param data: 的定义中所写的那样:(可选)要在 :class:Request 的正文中发送的字典、字节或类似文件的对象。
  • 我也试过 r = requests.post(urlToHit, json=body_, headers=headers_) 查看文档,但结果没有变化。
  • 这是一个旧帖子,但您是否在请求中尝试过data = json.dumps(body)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
相关资源
最近更新 更多