【问题标题】:POST multipart/form-data postman vs python requestPOST multipart/form-data 邮递员与 python 请求
【发布时间】:2021-02-09 18:43:34
【问题描述】:

我想使用 python 请求将 multipart/form-data 作为帖子正文发送,但我没有收到错误的请求问题。

import requests
headers = {"Content-Type": "multipart/form-data"}


data = {
    "@context": "http://semantro.com/", "@type": "KiranaSearch", "actionName": "listCategoryProducts",
    "pageLimit": {"@context": "http://semantro.com/", "@type": "PageProperty", "start": 0, "end": 24},
    "data": {"@context": "http://semantro.com/", "@type": "KiranaCategory",
             "identifier": "c5394d1d5c6c4cb8-adc77dd996876dba"}
}

response = requests.post('https://merokirana.com/semantro-web-interface/query',
                         data=data, headers=headers)

print(response.text)

回应

 {
  "statusTitle" : "ServiceUnsuccessful",
  "statusMessage" : "Invalid type of data received. The request  should have multipart query data.",
  "@context" : "http://semantro.com",
  "@type" : "RemoteServiceStatus"
}

但我可以使用 postman 相同的 formdata 检索所需的数据。

【问题讨论】:

  • 邮递员在请求中添加了哪些标头?
  • 内容类型、内容长度、主机、用户代理、接受、接受编码、连接
  • 您是否尝试将这些标头复制到您的请求中?
  • 不,他们没有工作。

标签: python request postman multipartform-data


【解决方案1】:
import http.client
import mimetypes
from codecs import encode

conn = http.client.HTTPSConnection("merokirana.com")
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=data;'))

dataList.append(encode('Content-Type: {}'.format('text/plain')))
dataList.append(encode(''))

dataList.append(encode("{ \"@context\": \"http://semantro.com/\", \"@type\": \"KiranaSearch\", \"actionName\": \"listCategoryProducts\",\"pageLimit\": {\"@context\": \"http://semantro.com/\", \"@type\": \"PageProperty\", \"start\": 0, \"end\": 24}, \"data\": {\"@context\": \"http://semantro.com/\", \"@type\": \"KiranaCategory\",\"identifier\": \"c5394d1d5c6c4cb8-adc77dd996876dba\"}}"))
dataList.append(encode('--'+boundary+'--'))
dataList.append(encode(''))
body = b'\r\n'.join(dataList)
payload = body
headers = {
   'Content-type': 'multipart/form-data; boundary={}'.format(boundary) 
}
conn.request("POST", "/semantro-web-interface/query", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

输出:

【讨论】:

  • 您不会收到请求命令的响应。复制我的答案。它肯定会给出想要的答案。
  • 是的,这项工作。我想调试问题所在。如果一切都失败了,我肯定会使用它。
  • 我认为问题在于有效载荷的嵌套结构。
  • 我对您的代码进行了一些调整,以便在请求中使用它。 Python 请求不适用于嵌套的 json。感谢您的帮助。
  • 仅供参考,如果你想添加一个文件作为数据,不要用 encode() 包装它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多