【问题标题】:python parse http response (string)python解析http响应(字符串)
【发布时间】:2014-09-03 20:54:17
【问题描述】:

我正在使用 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

提前致谢,

【问题讨论】:

    标签: python http


    【解决方案1】:

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

    另请注意,响应字符串中的内容长度标头可能不再有效(这取决于您如何获取这些响应)这只是意味着对 HTTPResponse.read() 的调用需要具有更大的值比内容更重要。

    在python 2中可以这样运行。

    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
    

    在python 3中,HTTPResponse是从http.client导入的,需要解析的响应需要字节编码。根据从哪里获取数据,可能已经完成或需要显式调用

    from http.client import HTTPResponse
    from io import BytesIO
    
    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
    
    teststring"""
    
    http_response_bytes = http_response_str.encode()
    
    class FakeSocket():
        def __init__(self, response_bytes):
            self._file = BytesIO(response_bytes)
        def makefile(self, *args, **kwargs):
            return self._file
    
    source = FakeSocket(http_response_bytes)
    response = HTTPResponse(source)
    response.begin()
    print( "status:", response.status)
    # status: 200
    print( "single header:", response.getheader('Content-Type'))
    # single header: text/xml; charset="utf-8"
    print( "content:", response.read(len(http_response_str)))
    # content: b'teststring'
    

    【讨论】:

    • 这看起来确实像我需要的技巧。为了我的简单目的,我可能可以通过使用正则表达式来解决问题,但使用 HTTPResponse 感觉更正确。非常感谢。
    • 作为后续,经过测试,是的,这是我想要的。
    • 但是如果有保持连接的连接呢?我们可以使用此解决方案解析多个标题/正文吗?类似于这个未回答问题的示例:stackoverflow.com/questions/34786880/…
    • 对于python3你可以使用from http.client import HTTPResponse
    • 有人用 Python3 完成了这项工作吗?我在File "/usr/lib/python3.6/http/client.py", line 258, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") 收到TypeError: decoding str is not supported
    【解决方案2】:

    您可能需要考虑使用 python-requests。

    链接:http://docs.python-requests.org/en/latest/

    这是来自http://dancallahan.info/journal/python-requests/的示例

    考虑到您的响应符合 HTTP RFC

    这看起来像你想做的事吗?

    >>> import requests
    >>> url = 'http://example.test/'
    >>> response = requests.get(url)
    >>> response.status_code
    200
    >>> response.headers['content-type']
    'text/html; charset=utf-8'
    >>> response.content
    u'Hello, world!'
    

    【讨论】:

    • 这如何回答这个问题?
    • 如何将已经存在的响应字符串加载到其中?
    • 这是一个无关紧要的答案。问题是关于解析已经存在的完整响应字符串而不是本身发出请求。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多