【问题标题】:How to use urllib3 to POST x-www-form-urlencoded data如何使用 urllib3 发布 x-www-form-urlencoded 数据
【发布时间】:2020-06-15 16:38:50
【问题描述】:

我正在尝试在 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 API 吗?

【问题讨论】:

    标签: python api servicenow urllib3


    【解决方案1】:

    根据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()(根据相同的文档)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 2018-12-25
      • 2021-03-14
      • 2017-02-13
      相关资源
      最近更新 更多