Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4604630
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T00:19:21+00:00 2026-05-22T00:19:21+00:00

I have a string of raw HTTP and I would like to represent the

  • 0

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?

'GET /search?sourceid=chrome&ie=UTF-8&q=ergterst HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\nUser-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.45 Safari/534.13\r\nAccept-Encoding: gzip,deflate,sdch\r\nAvail-Dictionary: GeNLY2f-\r\nAccept-Language: en-US,en;q=0.8\r\n
[...]'
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T00:19:22+00:00Added an answer on May 22, 2026 at 12:19 am

    Update: It’s 2019, so I have rewritten this answer for Python 3, following a confused comment from a programmer trying to use the code. The original Python 2 code is now down at the bottom of the answer.

    There are excellent tools in the Standard Library both for parsing RFC 821 headers, and also for parsing entire HTTP requests. Here is an example request string (note that Python treats it as one big string, even though we are breaking it across several lines for readability) that we can feed to my examples:

    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'
    )
    

    As @TryPyPy points out, you can use Python’s email message library to parse the headers — though we should add that the resulting Message object acts like a dictionary of headers once you are done creating it:

    from email.parser import BytesParser
    request_line, headers_alone = request_text.split(b'\r\n', 1)
    headers = BytesParser().parsebytes(headers_alone)
    
    print(len(headers))     # -> "3"
    print(headers.keys())   # -> ['Host', 'Accept-Charset', 'Accept']
    print(headers['Host'])  # -> "cm.bell-labs.com"
    

    But this, of course, ignores the request line, or makes you parse it yourself. It turns out that there is a much better solution.

    The Standard Library will parse HTTP for you if you use its BaseHTTPRequestHandler. Though its documentation is a bit obscure — a problem with the whole suite of HTTP and URL tools in the Standard Library — all you have to do to make it parse a string is (a) wrap your string in a BytesIO(), (b) read the raw_requestline so that it stands ready to be parsed, and (c) capture any error codes that occur during parsing instead of letting it try to write them back to the client (since we do not have one!).

    So here is our specialization of the Standard Library class:

    from http.server import BaseHTTPRequestHandler
    from io import BytesIO
    
    class HTTPRequest(BaseHTTPRequestHandler):
        def __init__(self, request_text):
            self.rfile = BytesIO(request_text)
            self.raw_requestline = self.rfile.readline()
            self.error_code = self.error_message = None
            self.parse_request()
    
        def send_error(self, code, message):
            self.error_code = code
            self.error_message = message
    

    Again, I wish the Standard Library folks had realized that HTTP parsing should be broken out in a way that did not require us to write nine lines of code to properly call it, but what can you do? Here is how you would use this simple class:

    # Using this new class is really easy!
    
    request = HTTPRequest(request_text)
    
    print(request.error_code)       # None  (check this first)
    print(request.command)          # "GET"
    print(request.path)             # "/who/ken/trust.html"
    print(request.request_version)  # "HTTP/1.1"
    print(len(request.headers))     # 3
    print(request.headers.keys())   # ['Host', 'Accept-Charset', 'Accept']
    print(request.headers['host'])  # "cm.bell-labs.com"
    

    If there is an error during parsing, the error_code will not be None:

    # Parsing can result in an error code and message
    
    request = HTTPRequest(b'GET\r\nHeader: Value\r\n\r\n')
    
    print(request.error_code)     # 400
    print(request.error_message)  # "Bad request syntax ('GET')"
    

    I prefer using the Standard Library like this because I suspect that they have already encountered and resolved any edge cases that might bite me if I try re-implementing an Internet specification myself with regular expressions.

    Old Python 2 code

    Here’s the original code for this answer, back when I first wrote it:

    request_text = (
        'GET /who/ken/trust.html HTTP/1.1\r\n'
        'Host: cm.bell-labs.com\r\n'
        'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n'
        'Accept: text/html;q=0.9,text/plain\r\n'
        '\r\n'
        )
    

    And:

    # Ignore the request line and parse only the headers
    
    from mimetools import Message
    from StringIO import StringIO
    request_line, headers_alone = request_text.split('\r\n', 1)
    headers = Message(StringIO(headers_alone))
    
    print len(headers)     # -> "3"
    print headers.keys()   # -> ['accept-charset', 'host', 'accept']
    print headers['Host']  # -> "cm.bell-labs.com"
    

    And:

    from BaseHTTPServer import BaseHTTPRequestHandler
    from StringIO import StringIO
    
    class HTTPRequest(BaseHTTPRequestHandler):
        def __init__(self, request_text):
            self.rfile = StringIO(request_text)
            self.raw_requestline = self.rfile.readline()
            self.error_code = self.error_message = None
            self.parse_request()
    
        def send_error(self, code, message):
            self.error_code = code
            self.error_message = message
    

    And:

    # Using this new class is really easy!
    
    request = HTTPRequest(request_text)
    
    print request.error_code       # None  (check this first)
    print request.command          # "GET"
    print request.path             # "/who/ken/trust.html"
    print request.request_version  # "HTTP/1.1"
    print len(request.headers)     # 3
    print request.headers.keys()   # ['accept-charset', 'host', 'accept']
    print request.headers['host']  # "cm.bell-labs.com"
    

    And:

    # Parsing can result in an error code and message
    
    request = HTTPRequest('GET\r\nHeader: Value\r\n\r\n')
    
    print request.error_code     # 400
    print request.error_message  # "Bad request syntax ('GET')"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If I have a raw HTTP response as a string: HTTP/1.1 200 OK Date:
I would like to convert a raw string to an array of big-endian words.
Does Objective-C have raw strings like Python's ? Clarification: a raw string doesn't interpret
I have string like this /c SomeText\MoreText Some Text\More Text\Lol SomeText I want to
I have string like \LESSING\root\cimv2:Win32_UserAccount.Domain=LESSING,Name=Admin How to convert it to LESSING\Admin using Framework?
I have string like this: G:\Projects\TestApp\TestWeb\Files\Upload\file.jpg How can I remove all text before Files
I have string looking like this: 'Toy Story..(II) (1995)' I want to split the
I have string column with numbers in a datagridview.It is not bound, I would
I have a string which consists of the raw HTML of a webpage. I
Situation: I have an ArrayList<String> containing a bunch of links to images (http:/www.foo.com/bar/image1.jpg, http:/www.foo.com/bar/image2.png,...

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.