GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, May 2, 2011

Python - Build Web Client

This is a small code for emulating on how to a web client connect to server:

file: client.py
import socket

HOST = 'localhost'
PORT = 6003
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

# request line
http_data = 'GET /index.php HTTP/1.1\n'

# header line - all are optional but Host
http_data = http_data + 'Host: localhost:80\n'  # required
http_data = http_data + 'From: irfan.ub@gmail.com\n'
http_data = http_data + 'User-Agent: Lucia Browser\n'
http_data = http_data + 'Keep-Alive: 10\n'
http_data = http_data + 'Accept: text/html\n'
http_data = http_data + 'Connection: close\n'

# separation line - required
http_data = http_data + '\n'    # required

client.send(http_data)

data = client.recv(1024*5)
client.close()
print 'Received\n=================\n', data

The response header is like this:
Received
=================
HTTP/1.1 200 OK
Date: Sun, 01 May 2011 22:19:28 GMT
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_
color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.1
Set-Cookie: PHPSESSID=ajunliavga128hlvcou4chigv6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 114
Connection: close
Content-Type: text/html

<form action="test.php" method="post">
<input type="text" name="text"/> Holla</form>
<a href="test.php">Test</a>
Share/Bookmark

No comments:

Post a Comment