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.
- prepare a request object, that is created for a given URI.
- write the PARAMETERS string to the request stream.
- 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:
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?
Magnus,
urllib2 uses some 'undocumented' attributes of sockets that weren't implemented in IronPython.
Post a Comment