python表单数据系统_使用MultipartPostHandler用Python发布表单数据

问题:使用Python的urllib2发布数据时,所有数据都是URL编码的,并作为内容类型发送:application/x-www-form-URL encoded。上载文件时,应将内容类型设置为multipart/form data,并对内容进行MIME编码。

为了克服这个限制,一些精明的程序员创建了一个名为MultipartPostHandler的库,它创建了一个OpenerDirector,您可以与urllib2一起使用,以大多数情况下自动发布多部分/表单数据。这个库的副本在这里:MultipartPostHandler doesn't work for Unicode files

我是Python新手,无法使用这个库。我基本上写出了下面的代码。当我在本地HTTP代理中捕获它时,我可以看到数据仍然是URL编码的,而不是多部分MIME编码的。请帮我弄清楚我做错了什么,或者用更好的方法来完成这件事。谢谢:-)FROM_ADDR = 'my@email.com'

try:

data = open(file, 'rb').read()

except:

print "Error: could not open file %s for reading" % file

print "Check permissions on the file or folder it resides in"

sys.exit(1)

# Build the POST request

url = "http://somedomain.com/?action=analyze"

post_data = {}

post_data['analysisType'] = 'file'

post_data['executable'] = data

post_data['notification'] = 'email'

post_data['email'] = FROM_ADDR

# MIME encode the POST payload

opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)

urllib2.install_opener(opener)

request = urllib2.Request(url, post_data)

request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy

# Make the request and capture the response

try:

response = urllib2.urlopen(request)

print response.geturl()

except urllib2.URLError, e:

print "File upload failed..."

编辑1:谢谢你的回复。我知道ActiveState的httplib解决方案(我链接到上面)。我宁愿抽象掉这个问题,用最少的代码继续使用urllib2。知道为什么没有安装和使用开瓶器吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值