您的位置:首页 > 其它

Submit a POST form and download the result web page

2012-12-13 15:37 411 查看
Submit a POST form and download the result web page - IronPython Cookbook

Submit a POST form and download the result web page

From IronPython Cookbook

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
This uses the System.Net.WebRequest class.

Here is a simple function, which works whether you are making a 'POST' or a 'GET':

from System.Net import WebRequest
from System.IO import StreamReader
from System.Text import Encoding

def UrlOpen(uri, parameters=None):
request = WebRequest.Create(uri)
if parameters is not None:
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
bytes = Encoding.ASCII.GetBytes(parameters)
request.ContentLength = bytes.Length
reqStream = request.GetRequestStream()
reqStream.Write(bytes, 0, bytes.Length)
reqStream.Close()

response = request.GetResponse()
result = StreamReader(response.GetResponseStream()).ReadToEnd()
return result

Back to Contents.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐