A simple HTTP client made after practicing Python
Python 3.4.3
If the command is python3, please read as appropriate.
$python http1.0.py 'ip address' 'File name to save the returned html'
Since it was troublesome to write the skipping of the header, I searched all the parts with two consecutive line breaks from the front and cut them off with slices. The exception is the style of catching everything for the time being.
http1.0.py
import socket
import sys
import traceback
def main():
#Set max buffer size
max_size = 8192
argv = sys.argv
argc = len(argv)
#Check commandline parameter
if(argc != 3):
sys.stderr.write('Usage: python http1.0.py [ADDRESS] [FILE]\nor\n')
sys.stderr.write('Usage: python3 http1.0.py [ADDRESS] [FILE]\n')
exit()
address = (argv[1], 80)
filename = argv[2]
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create socket
client.connect(address) #Connect
client.sendall(b'GET / HTTP/1.0\r\n\r\n') #Send GET command
data = client.recv(max_size).decode('utf-8') #Receive data and decode
client.close() #Close
#Cut header
index = data.find('\r\n\r\n')
data = data[index:]
#Write HTML file
fout = open(filename, 'w')
fout.write(data)
fout.close()
except:
sys.stderr.write(traceback.format_exc())
exit()
if __name__ == '__main__':
main()
Recommended Posts