python解析http响应(字符串)

abd*_*lam 12 python http

我正在使用python 2.7,我想解析我已经从文本文件中提取的字符串HTTP响应字段.什么是最简单的方法?我可以使用BaseHTTPServer解析请求,但无法找到响应的内容.

我的回答非常标准,并采用以下格式

HTTP/1.1 200 OK
Date: Thu, Jul  3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626
Run Code Online (Sandbox Code Playgroud)

提前致谢,

Jer*_*len 21

您可能会发现这很有用,请记住,HTTPResponse并非旨在"由用户直接实例化".

另请注意,响应字符串中的内容长度标头可能不再有效(这取决于您获取这些响应的方式)这只是意味着对HTTPResponse.read()的调用需要具有大于内容的值为了得到这一切.

这个例子是特定于python v2的,在v3-ish中,StringIO和httplib的导入位置已经改变.

from httplib import HTTPResponse
from StringIO import StringIO

http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul  3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626"""

class FakeSocket():
    def __init__(self, response_str):
        self._file = StringIO(response_str)
    def makefile(self, *args, **kwargs):
        return self._file

source = FakeSocket(http_response_str)
response = HTTPResponse(source)
response.begin()
print "status:", response.status
print "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
Run Code Online (Sandbox Code Playgroud)

  • 对于python3,你可以使用from from http.client import HTTPResponse (2认同)