Skip to content

Instantly share code, notes, and snippets.

@macagua
Last active October 4, 2018 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macagua/58f85dc8905cec78dfa085eab2b15bfb to your computer and use it in GitHub Desktop.
Save macagua/58f85dc8905cec78dfa085eab2b15bfb to your computer and use it in GitHub Desktop.
HTTP Server request and response for GET and POST verbs demostration with Python 3

README

To use this:

  1. Install httpie via pip inside a virtualenv, executing the following command: pip install httpie
  2. Execute HTTP Server script on your machine, executing the following command: python3 my-httpserver.py
  3. Test a HEAD request using http script from httpie package, executing the following command: http -v HEAD http://127.0.0.1:8085/

    The response it should be like the following:

    HEAD / HTTP/1.1

    Accept: /

    Accept-Encoding: gzip, deflate

    Connection: keep-alive

    Host: 127.0.0.1:8085

    User-Agent: httpie/0.9.9

    HTTP/1.0 200 OK

    Content-type: text/html

    Date: Thu, 04 Oct 2018 02:26:54 GMT

    Server: BaseHTTP/0.6 Python/3.5.3

  4. Test a GET request using http script from httpie package, executing the following command: python3 my-httpclient.py 127.0.0.1:8085 then it show like this:

    HTTP Client is starting...

    Enter a input command (example GET test.html, type "exit" to end it):

    Them you can enter a input command like GET test.html and the response it should be like the following:

    200 OK

    b'<html>n <head>n <title>HTTP GET verb</title>n </head>n <body>n <h1>This is a GET verb!</h1>n </body>n</html>n'

  5. Test a POST request using http script from httpie package, executing the following command: http --form POST http://127.0.0.1:8085/ message="Hello World"

    The response it should be like the following:

    HTTP/1.0 200 OK

    Content-type: text/html

    Date: Thu, 04 Oct 2018 12:24:09 GMT

    Last-Modified: Thu, 04 Oct 2018 12:24:09 GMT

    Server: BaseHTTP/0.6 Python/3.5.3

    HTTP/1.0 200 OK

    Server: BaseHTTP/0.6 Python/3.5.3

    Date: Thu, 04 Oct 2018 12:24:09 GMT

    Content-type: text/html

    Last-Modified: Thu, 04 Oct 2018 12:24:09 GMT

    <html>

    <body>

    <h1>POST verb demo</h1>

    <p>The message is 'Hello World'.</p>

    <br />

    <p>This is a POST verb!</p>

    </body>

    </html>

import http.client
import sys
def run(http_server):
print('HTTP Client is starting...')
try:
# create a connection
connection = http.client.HTTPConnection(http_server, timeout=10)
while 1:
command = input('\nEnter a input command (example GET test.html, type "exit" to end it): ')
command = command.split()
if command[0] == 'exit': # type exit to end it
print ("\nStopping web client....")
break
# request command to server
connection.request(command[0], command[1])
# get response from server
response = connection.getresponse()
# print server response and data
print(response.status, response.reason)
data_received = response.read()
print(data_received)
connection.close()
except KeyboardInterrupt:
print (" o <Ctrl-C> entered, stopping HTTP Client....")
connection.close()
if __name__ == '__main__':
''' Starting Python program '''
if not sys.argv[1:]:
print ("Fatal: You forgot to include the URL like 127.0.0.1:8085 from the my3-httpserver.py module on the command line.")
print ("Usage: python3 {0} IP:PORT".format(sys.argv[0]))
sys.exit(2)
else:
# get http server ip
http_server = sys.argv[1]
run(http_server)
elif __name__ == "my-httpclient":
initialize()
else:
print ("This program is bad configured, you should be call to the module....")
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import time
import cgi
# ip and port of server
HOST_NAME = '127.0.0.1'
# by default http server port is 8085
PORT_NUMBER = '8085'
class MyHTTPRequestHandler(BaseHTTPRequestHandler):
""" Create custom HTTPRequestHandler class """
def _set_headers(self):
""" set HTTP headers """
# send code 200 response
self.send_response(200)
# send header first
self.send_header('Content-type', 'text/html')
self.send_header('Last-Modified',
self.date_time_string(time.time()))
# send file content to client
self.end_headers()
def do_HEAD(self):
""" do the HTTP HEAD """
# set HTTP headers
self._set_headers()
def do_GET(self):
""" handle GET command """
rootdir = os.path.dirname(__file__) # file location
try:
if self.path.endswith('.html'):
f = open(rootdir + self.path) # open requested file
# set headers
self._set_headers()
# send file content to client
self.wfile.write(bytes(f.read(), "utf-8"))
f.close()
return
except IOError:
self.send_error(404, 'file not found')
def do_POST(self):
""" handle POST command """
# set HTTP headers
self._set_headers()
# Create instance of FieldStorage
# for parse the form data posted
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
# Begin the response
self._set_headers()
# Get data from fields
message = form.getvalue('message')
html_response = """
<html>
<body>
<h1>POST verb demo</h1>
<p>The message is '%s'.</p>
<br />
<p>This is a POST verb!</p>
</body>
</html>
""" % (message)
self.wfile.write(bytes(html_response, "utf-8"))
def run():
try:
print('HTTP Server is starting...')
server_address = (HOST_NAME, int(PORT_NUMBER))
server = HTTPServer(server_address, MyHTTPRequestHandler)
print ("HTTP Server running on http://{0}:{1}/ use <Ctrl-C> to stop.".format(HOST_NAME, PORT_NUMBER))
server.serve_forever()
except KeyboardInterrupt:
print (" o <Ctrl-C> entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
""" Starting Python program """
run()
elif __name__ == "my-httpserver":
initialize()
else:
print ("This program is bad configured, you should be call to the module....")
<html>
<head>
<title>HTTP GET verb</title>
</head>
<body>
<h1>This is a GET verb!</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment