Python HTTP Post client
とりあえず、、、そろそろ Python も触ってみようかと思って書いてみた。たいしたことはやっていないけれども。とりあえずこれだけ。
KeepAlive & Content-Length
import socket HOST = '10.0.0.1' port = 80 POST_DATA = "username=administrator" client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST,port)) client.send('POST / HTTP/1.1\r\n') client.send('Host: ' + HOST + '\r\n') client.send('Connection: KeepAlive\r\n') client.send('Content-Type: application/x-www-form-urlencoded\r\n') client.send('Content-Length: ' + str(len(POST_DATA)) + '\r\n') client.send('\r\n') client.send(POST_DATA) stream = client.makefile() responseLength = 0 # Read Header while True: data = stream.readline() if data.startswith('Content-Length'): responseLength = data.split(' ')[1] print data if data == '\r\n': break print "responseLength is " + responseLength # Read Body response = '' for i in range(0, int(responseLength)): response = response + stream.read(1) print response client.close()
KeepAlive & TransferEncoding chunked
import socket HOST = '10.0.0.1' port = 80 POST_DATA = "username=administrator" client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((HOST,port)) client.send('POST / HTTP/1.1\r\n') client.send('Host: ' + HOST + '\r\n') client.send('Connection: KeepAlive\r\n') client.send('Content-Type: text/xml;charset=UTF-8\r\n') client.send('Transfer-Encoding: chunked\r\n') client.send('\r\n') client.send(POST_DATA) stream = client.makefile() responseLength = 0 # Read Header while True: data = stream.readline() if data.startswith('Content-Length'): responseLength = data.split(' ')[1] print data if data == '\r\n': break print "responseLength is " + responseLength # Read Body response = '' for i in range(0, int(responseLength)): response = response + stream.read(1) print response client.close()