如何更改内容类型Python [英] How to Change Content-Type Python
问题描述
我想将文件上传到远程设备. 如果我通过Wireshark查找连接,我会得到这个
I want to upload a file to a remote device. If i look up the connection with wireshark i get this
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
Now this says that that the browser only accepts text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
如果我使用脚本上传文件,则显示
If i upload the file with my script it says
--0a7125aebb8845ba8ab9aa21306b01f6
Content-Disposition: form-data; name="restore"; filename="Config.cfg"
Content-Type: text/plain; charset=utf-8
所以这是错误的文件类型.
So it's a wrong file type..
那我该如何更改文件的内容类型?
so how do i change the content-type of the File ?
我的代码看起来如下:
#!/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()
推荐答案
在 poster.encode.MultipartParam
的文档说:
In the documentation for poster.encode.MultipartParam
it says:
如果设置了
filetype
,它将用作此参数的Content-Type.如果未设置,则默认为文本/纯文本;默认为纯文本". charset = utf8"
If
filetype
is set, it is used as the Content-Type for this parameter. If unset it defaults to "text/plain; charset=utf8"
所以不要像这样指定参数:
So instead of specifying your parameters like this:
params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'}
像这样指定他们:
params = [MultipartParam('restore', open("Config.cfg", "rb"),
filetype = 'application/octet-stream'),
('upload', 'PC ==>; Unit')]
这篇关于如何更改内容类型Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!