在Python中更改内容类型

时间:2012-10-01 13:47:15

标签: python post content-type

所以我尝试在远程设备上上传文件。

如果我使用代码:

#!/usr/bin/python

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

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

datagen, headers = multipart_encode(params)

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

该文件已上载Content-Type text / plain ..

那么如何将此内容类型更改为text / html?

2 个答案:

答案 0 :(得分:4)

添加:

headers['Content-Type'] = 'text/html'

在实例化Request对象之前。

答案 1 :(得分:1)

您可以使用python中的mechanize lib:

import mechanize
b = mechanize.Browser()

# Set any header you like:
b.addheaders = [('Content-Typoe', 'text/html; charset=utf-8')]
response = b.open('http://www.reddit.com')
data = response.read()