POST multipart/formdata postman vs python请求

2024-09-29 23:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python请求将一个多部分/表单数据作为post正文发送,但我并没有收到错误的请求问题

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"
}

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

enter image description here


Tags: 数据comhttp表单dataresponsetype错误
1条回答
网友
1楼 · 发布于 2024-09-29 23:32:53
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"))

输出:

enter image description here

相关问题 更多 >

    热门问题