【问题标题】:Use Python Requests to do post request in postman在 postman 中使用 Python Requests 做 post 请求
【发布时间】:2020-03-23 09:12:57
【问题描述】:

我需要使用 Python 向 API 服务器发送 post 请求。

我在 Postman 中所做的如下所示。

此请求需要这些标头:

{
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
}

我希望代码 200 和类似的东西

{
    "data": {
        "image": "mypic"
    }
}

如何通过 Python 发送此请求?

我做了一些类似的测试

r = requests.Request(method='POST', url='https://api.myapi.site/api/post', headers={
    'Accept': 'application/json',
    'Content-Type': 'multipart/form-data'
}, data={
    'identifier': 'test',
    'token': 'db642912e1a431651c8776',
    'image': open('mypic.png', 'rb')
}).prepare()
s = requests.Session()
rsp = s.send(r)
s.close()

但这不是答案,得到了 401 回报,

服务器说我发送了一个带有“form-urlencoded”标头的请求。

所以也许它不是通过数据参数发送的,

但我尝试使用参数,服务器说我发送的数据太大。

请帮忙!

【问题讨论】:

  • 运行代码时遇到什么错误?当你向邮递员提出要求时,你会得到什么结果?请同时更新您的问题。
  • @lee-pai-long 我更新了我的问题。谢谢!
  • 您可能缺少一些 cookie,XSRF-TOKEN 也有类似的问题。在我的情况下 client = requests.session() client.get(url) csrf_token = client.cookies['XSRF-TOKEN'].replace('%3D', '=') 帮助

标签: python post postman


【解决方案1】:

'image': open('mypic.png', 'rb') 似乎有问题 它是文件对象,但您想发送字节。试试:

'image': open('mypic.png', 'rb').read()

【讨论】:

    【解决方案2】:

    试试:

    response = requests.post(SERVER_URL, headers={}, data={}, files={"file": open(file_path, 'rb')}, timeout=200)
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 2015-05-18
      • 2017-12-25
      • 1970-01-01
      • 2019-10-11
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多