使用python请求通过POST发送图像 - python

我正在尝试使用以下代码发送图像:这只是我的代码的一部分,我没有在此处包括标头,但它们的设置正确,内容类型为content-type: multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe

img = "piano.jpg"
f = open(img,'rb')
out = f.read()
files = {'file':out}

p = requests.post("https://ecg-api.gumtree.com.au/api/pictures",headers=headers, data=files)
f.close()

我收到400错误incorrect multipart/form-data format

如何正确发送图像?

额外详情:

网络分析显示已发送以下请求:

POST https://ecg-api.gumtree.com.au/api/pictures HTTP/1.1
host:   ecg-api.gumtree.com.au
content-type:   multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe
authorization:  Basic YXV5grehg534
accept: */*
x-ecg-ver:  1.49
x-ecg-ab-test-group:    gblios_9069_b;gblios-8982-b
accept-encoding:    gzip
x-ecg-udid: 73453-7578p-8657
x-ecg-authorization-user:   id="1635662", token="ee56hgjfjdghgjhfj"
accept-language:    en-AU
content-length: 219517
user-agent: Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)
x-ecg-original-machineid:   Gk435454-hhttehr

Form data:
file: ����..JFIF.....H.H..��.LExif..MM.*..................�i.........&......�..

我切断了文件的formdata部分,因为它太长了。我的标头编写如下(我在这里构成了实际的auth值):

idd = "1635662"
token = "ee56hgjfjdghgjhfj"

headers = {
"authority":"ecg-api.gumtree.com.au",
"content-type":"multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe",
"authorization":"Basic YXV5grehg534",
"accept":"*/*",
"x-ecg-ver":"1.49",
"x-ecg-ab-test-group":"gblios_9069_b;gblios-8982-b",
"accept-encoding":"gzip",
"x-ecg-udid":"73453-7578p-8657",
"x-ecg-authorization-user":f"id={idd}, token={token}",
"accept-language":"en-AU",
"content-length":"219517",
"user-agent":"Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)",
"x-ecg-original-machineid":"Gk435454-hhttehr"
}

也许是我编写标题的方式?我怀疑这是我在标题中编写x-ecg-authorization-user部分的方式吗?因为我意识到即使为令牌或id放置随机值也会给我同样的400错误incorrect multipart/form-data format

参考方案

您可以尝试以下代码。不要在标题中设置内容类型,让Pyrequests为您做到这一点

files = {'file': (os.path.basename(filename), open(filename, 'rb'), 'application/octet-stream')}
upload_files_url = "url"
headers = {'Authorization': access_token, 'JWTAUTH': jwt}
r2 = requests.post(parcels_files_url, files=files, headers=headers)

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

查找字符串中的行数 - python

我正在创建一个python电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …

字符串文字中的正斜杠表现异常 - python

为什么S1和S2在撇号位置方面表现不同?S1="1/282/03/10" S2="4/107/03/10" R1="".join({"N\'" ,S1,"\'" }) R2="".join({"N\'…