我正在尝试使用Python语言中的urllib3将x-www-form-urlencoded数据发送到ServiceNow API。通常的curl命令如下所示
curl -d "grant_type=password&client_id=<client_ID>&client_secret=<client_Secret>&username=<username>&password=<password>" https://host.service-now.com/oauth_token.do
到目前为止,我已经尝试了以下方法:
import urllib3
import urllib.parse
http = urllib3.PoolManager()
data = {"grant_type": "password", "client_id": "<client_ID>", "client_secret": "<client_Secret>", "username": "<username>", "password": "<password>"}
data = urllib.parse.urlencode(data)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
accesTokenCreate = http.request('POST', "https://host.service-now.com/outh_token.do", headers = headers, fields= data)
print(accesTokenCreate.data)
但是,它不会生成类似于curl命令的结果,并且会给出如下错误:
Traceback (most recent call last):
File "/VisualStudio/Python/ServiceNow.py", line 18, in <module>
accesTokenCreate = http.request('POST', "https://visierdev.service-now.com/outh_token.do", headers = headers, fields= data)
File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/request.py", line 80, in request
method, url, fields=fields, headers=headers, **urlopen_kw
File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/request.py", line 157, in request_encode_body
fields, boundary=multipart_boundary
File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/filepost.py", line 78, in encode_multipart_formdata
for field in iter_field_objects(fields):
File "/usr/local/homebrew/lib/python3.7/site-packages/urllib3/filepost.py", line 42, in iter_field_objects
yield RequestField.from_tuples(*field)
TypeError: from_tuples() missing 1 required positional argument: 'value'
有人能帮我理解一下如何正确使用urllib3将这些数据发布到ServiceNow应用程序接口吗?
发布于 2020-12-10 09:16:18
根据urlllib3 documentation,您没有正确使用request()
方法。具体来说,代码中的fields
参数不是“键/值字符串和键/文件元组的参数”。它不应该是URL编码字符串。
要修复您的代码,只需将request
调用的fields
参数更改为body
,如下所示:
accesTokenCreate = http.request(
'POST', "https://host.service-now.com/outh_token.do",
headers=headers, body=data)
更好的是,您可以使用request_encode_body()
函数并直接传入字段,而无需使用urlencode
-ing它,然后让该函数为您调用urllib.parse.urlencode()
(根据相同的文档)。
https://stackoverflow.com/questions/62392885
复制相似问题