Python请求模块为POST提供错误400(错误请求)

时间:2017-02-06 15:04:30

标签: python python-requests

我是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': 'Mon, 06 Feb 2017 14:51:59 GMT', 'Content-Type': 'application/json'}
400
{"Message":"''"}

我认为在

中传递body_时我犯了一些错误

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

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

1 个答案:

答案 0 :(得分:0)

您需要使用:

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

请浏览documentation