HTTPResponse没有content_type参数怎么办
时间: 2023-12-01 10:03:34 浏览: 35
如果你需要指定HTTP响应的Content-Type类型,你可以手动在响应头中添加Content-Type字段。你可以使用HTTPResponse对象的`getheaders()`方法获取响应头信息,然后通过字符串拼接的方式添加Content-Type字段。以下是一个示例代码:
```python
import http.client
conn = http.client.HTTPSConnection('www.example.com')
conn.request('GET', '/index.html')
response = conn.getresponse()
# 获取响应头信息
headers = response.getheaders()
# 构造新的响应头信息
new_headers = ''
for header in headers:
new_headers += '{}: {}\r\n'.format(header[0], header[1])
new_headers += 'Content-Type: text/html\r\n'
# 重建响应对象
new_response = http.client.HTTPResponse(response.fp)
new_response.msg = http.client.parse_headers(new_headers.splitlines())
new_response.fp = response.fp
new_response.debuglevel = response.debuglevel
# 打印新的响应头信息
print(new_response.getheaders())
```
在这个示例中,我们首先使用`getheaders()`方法获取原始响应的头信息,然后通过字符串拼接的方式添加Content-Type字段。接着,我们使用HTTPResponse对象的构造器创建一个新的响应对象,并将新的响应头信息传递给它。最后,我们使用新的响应对象打印响应头信息,其中包括我们添加的Content-Type字段。