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 = 'http://www.example.com'
PARAMETERS="lang=en&field1=1"

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)
reqStream.Close()

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

2 comments:

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...

Magnus,

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