且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用带有请求的multipart/form-data的POST的python设置边界

更新时间:2022-02-18 22:26:40

男孩,那是一台损坏的服务器.如果可以,请修复服务器.

Boy, that's one very broken server. If you can, fix the server instead.

您无法告诉requests选择哪个边界.您可以使用 email.mime程序包来构建自己的multipart/form-data有效内容:

You can't tell requests what boundary to pick. You can instead build your own multipart/form-data payload, using the email.mime package:

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

related = MIMEMultipart('form-data', '*****')  # second argument is the boundary.
file_part = MIMEApplication(
    open('1103290736_2016_03_23_13_32_55.zip', 'rb').read(),
    # optional: set a subtype: 'zip',
)
file_part.add_header('Content-disposition', 'form-data; name="uploadedfile"')
related.attach(file_part)

body = related.as_string().split('\n\n', 1)[1]
headers = dict(related.items())
headers['User-Agent'] = 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)'

r = session.post(url, data=body, headers=headers)

这将Content-Type: multipart/form-data; boundary="*****"设置为标题,并且正文使用*****作为边界(具有适当的--前缀和后缀).

This sets Content-Type: multipart/form-data; boundary="*****" as the header, and the body uses ***** as the boundary (with appropriate -- pre- and postfixes).