如何用头和体构造python post请求?

时间:2023-02-02 07:38:46

I am completely new to Python. I need to post an authentication request to a website using header and body details. I have posted the code below that I have so far. When I run it, I get syntax error on this line:

我对Python完全陌生。我需要使用header和body details向网站发布身份验证请求。到目前为止,我已经发布了下面的代码。当我运行它时,我在这行上得到语法错误:

req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2')

Can you please review and let me know where I've gone wrong?

你能不能帮我复习一下,告诉我哪里出错了?

import urllib.request
import json

body = {'identifier': 'my_id', 'password': 'my_encrypted_pwd', 'encryptedPassword': true}

url = 'https://mywebsite.com/gateway/deal/session'
req = urllib.request.Request(url)
req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('UTF-8')
req.add_header('Content-Length', len(jsondataasbytes))
print (jsondataasbytes)
response = urllib.request.urlopen(req, jsondataasbytes)

1 个解决方案

#1


1  

I suggest you should use the requests module, as it's faster and simply better than urllib.request:

我建议您使用request模块,因为它比urllib更快、更好。

response = requests.put(
        url,
        body, headers={'API-KEY': 'my_api_key',
                       'ACCOUNT-ID': 'my_account_id',
                       'Content-Type': 'application/json; charset=UTF-8',
                       'VERSION': '2'
              }
        )

Now you can parse the response you get as usual.

现在可以像往常一样解析得到的响应。

#1


1  

I suggest you should use the requests module, as it's faster and simply better than urllib.request:

我建议您使用request模块,因为它比urllib更快、更好。

response = requests.put(
        url,
        body, headers={'API-KEY': 'my_api_key',
                       'ACCOUNT-ID': 'my_account_id',
                       'Content-Type': 'application/json; charset=UTF-8',
                       'VERSION': '2'
              }
        )

Now you can parse the response you get as usual.

现在可以像往常一样解析得到的响应。