在调用第三方后端接口的时候,有个接口,它要求post请求头中,content-type必须为multipart/form-data的时候,一开始就是显示指定content-type格式,也就是在请求头headers={‘Content-Type’: multipart/form-data},导致form-data数据丢失,导致后端拿不到数据,一直报错
解决方法:
1、不要在请求头设置headers,直接传个files字段,这样就会自动识别为multipart/form-data格式,如果files字段没有值,可以自己构建一个,比如files={ ‘a’: None }
import reqeusts
request.post(url, data=data, files=files)
2、显示设置请求头,也就是上面出现bug的做法,但是需要做个格式
payload = f"""
--{boundary} Content-Disposition: form-data; name="advertiser_id" 11111
--{boundary} Content-Disposition: form-data; name="upload_type" UPLOAD_BY_URL
--{boundary} Content-Disposition: form-data; name="image_url" https://p26-sign.douyinpic.com/tos-cn-v-c9e10a/ogQzCTHJRedoTNEtRfaCteAQP2G74BHI8CvIbg~tplv-noop.image?x-expires=3366331560&x-signature=MkKM7TWMpNJ9xTcE0eCs%2Fxk%2Bps4%3D
--{boundary} Content-Disposition: form-data; name="filename" 0331-维达山茶花湿厕纸-原生2-y
--{boundary}--
"""
案例代码
import requests
import uuid
def upload_image():
open_api_url_prefix = "https://ad.oceanengine.com/open_api/"
uri = "2/file/image/ad/"
url = open_api_url_prefix + uri
files = None
# 生成边界值
boundary = '----WebKitFormBoundary' + str(uuid.uuid4())
# 构建 multipart/form-data 格式的数据
payload = f"""--{boundary}
Content-Disposition: form-data; name="advertiser_id"
17026
--{boundary}
Content-Disposition: form-data; name="upload_type"
UPLOAD_BY_URL
--{boundary}
Content-Disposition: form-data; name="image_url"
https://www.baidu.com
--{boundary}
Content-Disposition: form-data; name="filename"
文件名
--{boundary}--
"""
headers = {
"Access-Token": "xxxx",
"Content-Type": f"multipart/form-data; boundary={boundary}"
}
rsp = requests.post(url, data=payload.encode('utf-8'), headers=headers)
rsp_data = rsp.json()
return rsp_data
if __name__== '__main__':
upload_image()