Thursday, May 31, 2007

How to programmatically submit a POST form using IronPython

Sometimes you may want to download a web page that is a result of submitting a form that uses a POST method. The code below shows how to do that using IronPython.

  1. prepare a request object, that is created for a given URI.
  2. write the PARAMETERS string to the request stream.
  3. retrieve the response and read from its stream.

URI = ''

from System.Net import WebRequest
request = WebRequest.Create(URI)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"

from System.Text import Encoding
bytes = Encoding.ASCII.GetBytes(PARAMETERS)
request.ContentLength = bytes.Length
reqStream = request.GetRequestStream()
reqStream.Write(bytes, 0, bytes.Length)

response = request.GetResponse()
from System.IO import StreamReader
result = StreamReader(response.GetResponseStream()).ReadToEnd()
print result


Anonymous said...

Am I missing something?

Why would you want to use .net libraries when using urllib2 is so much easier, and more portable?

Is it not available for IronPython?

Andrzej Krzywda said...


urllib2 uses some 'undocumented' attributes of sockets that weren't implemented in IronPython.