您可能会发现这很有用,请记住HTTPResponse并非旨在“由用户直接实例化”。
还要注意,响应字符串中的content-
length标头可能不再有效(取决于您获取这些响应的方式),这仅意味着对HTTPResponse.read()的调用需要具有大于内容的值为了得到一切。
在python 2中,可以这种方式运行。
from httplib import HTTPResponsefrom StringIO import StringIOhttp_response_str = """HTTP/1.1 200 OKDate: Thu, Jul 3 15:27:54 2014Content-Type: text/xml; charset="utf-8"Connection: closeContent-Length: 626"""class FakeSocket(): def __init__(self, response_str): self._file = StringIO(response_str) def makefile(self, *args, **kwargs): return self._filesource = FakeSocket(http_response_str)response = HTTPResponse(source)response.begin()print "status:", response.statusprint "single header:", response.getheader('Content-Type')print "content:", response.read(len(http_response_str)) # the len here will give a 'big enough' value to read the whole content
在python
3中,
HTTPResponse从中导入
http.client,并且要解析的响应需要进行字节编码。根据从何处获取数据,可能已经完成或需要显式调用
from http.client import HTTPResponsefrom io import BytesIOhttp_response_str = """HTTP/1.1 200 OKDate: Thu, Jul 3 15:27:54 2014Content-Type: text/xml; charset="utf-8"Connection: closeContent-Length: 626teststring"""http_response_bytes = http_response_str.enpre()class FakeSocket(): def __init__(self, response_bytes): self._file = BytesIO(response_bytes) def makefile(self, *args, **kwargs): return self._filesource = FakeSocket(http_response_bytes)response = HTTPResponse(source)response.begin()print( "status:", response.status)# status: 200print( "single header:", response.getheader('Content-Type'))# single header: text/xml; charset="utf-8"print( "content:", response.read(len(http_response_str)))# content: b'teststring'
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)