使用带有请求的multipart/form-data的POST的python设置边界 [英] python set-up boundary for POST using multipart/form-data with requests

查看:396
本文介绍了使用带有请求的multipart/form-data的POST的python设置边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用请求发送文件,但服务器在*****处设置了固定边界.我只能发送文件,但是requests模块会创建随机边界.如何覆盖它?

I want to send a file using requests but the server works with a fixed boundary set at *****. I'm only able to send a file but the requests module creates a random boundary. How do I overwrite it?

import requests

url='http://xxx.xxx.com/uploadfile.php'
fichier= {'uploadedfile':open('1103290736_2016_03_23_13_32_55.zip','rb')}
headers2={'Connection':'Keep-Alive','User-Agent':'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)','Accept-Encoding':'gzip'}
session= requests.Session()
session.post(url,headers=headers2,files=fichier)
session.close()

推荐答案

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

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).

这篇关于使用带有请求的multipart/form-data的POST的python设置边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆