Parse raw HTTP Headers

前端 未结 7 1015

I have a string of raw HTTP and I would like to represent the fields in an object. Is there any way to parse the individual headers from an HTTP string?

\'GE         


        
7条回答
  •  日久生厌
    2020-11-27 05:01

    In a pythonic way

    request_text = (
        b'GET /who/ken/trust.html HTTP/1.1\r\n'
        b'Host: cm.bell-labs.com\r\n'
        b'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n'
        b'Accept: text/html;q=0.9,text/plain\r\n'
        b'\r\n'
    )
    
    print({ k:v.strip() for k,v in [line.split(":",1) 
            for line in request_text.decode().splitlines() if ":" in line]})
    

提交回复
热议问题