3

I wrote a HTTP server using python, but I do not know how to get the HTTP body. what should I do to get the HTTP body?

here is my code:

from http.server import HTTPServer,BaseHTTPRequestHandler

class MyHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print("connect from ",self.client_address)
        print(self.headers)
        length = self.headers['Content-Length']
        print(length)

addr = ('',21567)
server = HTTPServer(addr,MyHTTPHandler)
server.serve_forever()
8
  • Hmm. You might want to try Flask... Commented Jul 19, 2016 at 12:56
  • In any case. I feel like you should be writing HTML to some Response object Commented Jul 19, 2016 at 12:59
  • Possible duplicate of Writing response body with BaseHTTPRequestHandler Commented Jul 19, 2016 at 13:00
  • 1
    There is no HTTP body in a GET request...!? Commented Jul 19, 2016 at 13:00
  • 1
    @LiGhTx117 Well, yes, technically you can send any garbage you want... Commented Jul 19, 2016 at 13:14

1 Answer 1

2

Having a request body in a GET request is not a good practice, as its discussed here: HTTP GET with request body

Instead, you can change your method to POST and check there the BaseHTTPRequestHandler documentation: https://docs.python.org/2/library/basehttpserver.html

Especially this part:

rfile

Contains an input stream, positioned at the start of the optional input data.

Sign up to request clarification or add additional context in comments.

4 Comments

I've tried so many times, self.rfile.read(int(self.headers['Content-Length'])) returns nothing
What do you use to test you program (curl, web brower, etc.) ?
I've solved it, I changed the method to POST, and it finally worked!
@Enrico'sRicardo could you please accept this answer as solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.