浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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.

posted on 2012-12-13 15:37  lexus  阅读(382)  评论(0编辑  收藏  举报