Monday, October 6, 2014

Custom HTTP Server and adding 'custom http header attribute' while POST request

Well, python is used here to create a custom HTTP server which will behave like normal HTTP server for GET request but for POST request, it will send the received POST request header information back in response. Why done?  Just for fun but it can be used to do a lot more.

Python script:

import SimpleHTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import logging

class GetHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    
    def do_GET(self):
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
        return

    def do_POST(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(self.headers)
        return

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('', 8000), GetHandler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

Say script name is 'basehttp.py', you can run it using 'python basehttp.py'.

Here is the HTML Page  which play-around with this script.

<html>
<head>
<style>
div {
  border: 5px solid green;
}
</style>
</head>

<body>
<h1>This page will add the below 'Label(s)' into HTTP request header</h1><br>
<table>
<tr><td>Label1</td><td><input type="text" id="api-code1"></input></td></tr>
<tr><td>Label2</td><td><input type="text" id="api-code2"></input></td></tr>
<tr><td>Label3</td><td><input type="text" id="api-code3"></input></td></tr>
<tr><td></td><td><input type="submit" value="Submit" onClick='dojob()'></input></td></tr>
</table>
<br>
<div id="response"></div>
</body>

<script>
function dojob()
{
    xmlhttp=new XMLHttpRequest();

    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("response").innerHTML = "<h2> Header received on server was:</h2>";
        document.getElementById("response").innerHTML += "<pre>" + xmlhttp.response + "</pre>";
      }
    }

    xmlhttp.open("POST","test.html?t=" + Math.random(), false);
    xmlhttp.setRequestHeader("api-code1", document.getElementById("api-code1").value);
    xmlhttp.setRequestHeader("api-code2", document.getElementById("api-code2").value);
    xmlhttp.setRequestHeader("api-code3", document.getElementById("api-code3").value);
    xmlhttp.send();
}
</script>


Guess what is test.html here ? nothing, we just not using it in our POST request. Math.random() is used to invalidate the browser cache.