如何更改内容类型的Python

时间:2012-10-01 12:47:40

标签: python post content-type

我想将文件上传到远程设备。 如果我查看与wireshark的连接,我得到了这个

POST /saveRestore.htm.cgi HTTP/1.1
Host: 10.128.115.214
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://10.128.115.214/saveRestore.htm
Cache-Control: max-age=0
Content-Type: multipart/form-data; boundary=---------------------------961265085509552220604142744
Content-Length: 10708

-----------------------------961265085509552220604142744
Content-Disposition: form-data; name="restore"; filename="config(2).cfg"
Content-Type: application/octet-stream

现在这说明浏览器只接受text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8

如果我用我的脚本上传文件,则说

--0a7125aebb8845ba8ab9aa21306b01f6
Content-Disposition: form-data; name="restore"; filename="Config.cfg"
Content-Type: text/plain; charset=utf-8

所以这是一个错误的文件类型..

那么如何更改文件的内容类型?

我的代码看起来如下:

#!/usr/bin/python

import httplib
import urllib2
from poster.encode import multipart_encode
import poster
from poster.streaminghttp import register_openers
register_openers()

params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'}

datagen, headers = multipart_encode(params)

request = urllib2.Request('http://10.128.115.214/saveRestore.htm.cgi', datagen, headers)
u = urllib2.urlopen(request)
print u.read()

1 个答案:

答案 0 :(得分:2)

documentation for poster.encode.MultipartParam中说:

  

如果设置了filetype,则将其用作此参数的Content-Type。如果未设置,则默认为“text / plain;字符集= UTF8”

所以不要像这样指定你的参数:

params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'}

像这样指定:

params = [MultipartParam('restore', open("Config.cfg", "rb"),
                         filetype = 'application/octet-stream'),
          ('upload', 'PC ==>; Unit')]
相关问题