Проблема: при размещении данных с помощью Python urllib2 все данные кодируются в виде URL-адреса и отправляются в виде Content-Type: application/x-www-form-urlencoded. При загрузке файлов тип содержимого вместо этого должен быть установлен на multipart/form-data, а содержимое должно быть закодировано в MIME.
Чтобы обойти это ограничение, некоторые проницательные кодеры создали библиотеку с именем MultipartPostHandler, которая создает OpenerDirector, который вы можете использовать с urllib2, чтобы в большинстве случаев автоматически выполнять POST с multipart/form-data. Копия этой библиотеки находится здесь: MultipartPostHandler не работает для файлов Unicode
Я новичок в Python и не могу заставить эту библиотеку работать. Я написал по существу следующий код. Когда я записываю его в локальный HTTP-прокси, я вижу, что данные все еще имеют URL-кодировку, а не MIME-кодировку из нескольких частей. Пожалуйста, помогите мне понять, что я делаю неправильно, или лучший способ сделать это. Спасибо :-)
FROM_ADDR = '[email protected]'
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, как я был. Есть идеи, почему нож не устанавливается и не используется?