I usually do initial test/debug of my Android apps in a VirtualBox virtual machine before I go through the trouble of connecting a real device. These virtual devices see VirtualBox’s host-only network, usually 192.168.56.xx, for talking to the IDE, and have a second NAT‘ed adapter which uses the host’s Internet connection. On the host-only side, the host system gets address 192.168.56.1 and the VM gets a DHCP assignment on this subnet, like 192.168.56.101. This is also true if you are using something like Genymotion (which is really just wrapper around VirtualBox).
Many times, I’ve wished for a quick-and-dirty way to test apps in this environment against a web server that I control. I came across an easy way to do this, without having to install a full server like Apache. It uses Python 2.x‘s SimpleHTTPServer module. Here’s the code, which I adapted from a old Linux Journal tech tip:
#!/usr/bin/env python2 import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" if sys.argv[1:]: server = sys.argv[1] else: server = '127.0.0.1' if sys.argv[2:]: port = int(sys.argv[2]) else: port = 8000 server_address = (server, port) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) print "httpd on", server, ":", port httpd.serve_forever()
Put this in a .py
file like simple_web.py
and run it using python simple_web.py <address> <port>
(or make the file executable and run it directly). It will start a server and serve up files from the directory you started it in. Arguments are server address (1st argument) and port (2nd), with defaults of 127.0.0.1 (localhost
) and 8000, respectively. You can specify neither, just an address, or both address and port.
I kept this in Python 2.x since it’s the current default on my dev system (Ubuntu 14.04 LTS). If your setup has Python 3.x as the default, then you’ll have to either specify python2
on the command line, or translate the program to Python 3.x (hint: check out Python 3.x’s http.server
module).