python发HTTP post请求上传文件

可以使用第三方模块poster,使用easy_install 安装方法如下

easy_instll poster

会自动安装poster模块,安装成功后,可以看到在poster egg文件在site package下

这里注意,根据官方说法:Because this distribution was installed --multi-version, before we can import modules from this package, we need to 'import pkg_resources' and use 'require("poster")'. 

这是在试图卸载poster时(easy_install -m poster)时才看到的提示


下面是示例代码:

# -*- coding: utf-8 -*-
import httplib,urllib,re,urllib2,sys
from pkg_resources import require
require("poster==0.8.1")


from poster.encode import multipart_encode  
from poster.streaminghttp import register_openers

def uploadFile():
    try:
        register_openers()  
        #    opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) 
        params = {'Filename': open("httpRequestTestFile.xls", "rb"), 
                  'addr': 'importTax'}  
        datagen, headers = multipart_encode(params)  
        request = urllib2.Request(url, datagen, headers)  
        result = urllib2.urlopen(request).read()  
        print result 
    except Exception, e:
        print e

你可能感兴趣的:(测试)