控制台应用程序提交表单

2011-1-18 18:43:03 - tanlixiao

最近在做一控制台应用程序,程序读取IIS信息,根据读取的信息生成csv文件,以提供给IPMonitor导入,导入以网页地址和参数导入,是从应用程序提交表单,刚知道这项目一头雾水,然后再网上查找了相关的方法,我找到两个从控制端提交表单的方法,第一个用的还很顺利,调用其他页面时,没有问题,但是提交到本地的Ipmonitor页面时就报错,最后不用这一方法,再尝试用第二种方法,成功了;
代码如下:

        public static bool ClientPostForm(string address, string urlParam)
        {
            string formUrl = address;//url地址
            string formData = urlParam;
            CookieContainer cookieContainer = new CookieContainer();
            // 将提交的字符串数据转换成字节数组

            //注意提交的编码 这边是需要改变的 这边默认的是Default:系统当前编码
            byte[] postData = Encoding.Default.GetBytes(formData);

            // 设置提交的相关参数
            HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
            Encoding myEncoding = Encoding.GetEncoding("GBK");
if (ReadXml.ReadAuthenticate(ref credUserName,ref credPassWord))
{
//添加验证
request.PreAuthenticate = true;
NetworkCredential monitorcred = new NetworkCredential(credUserName, credPassWord);
request.Credentials = monitorcred;
}
            request.Method = "POST";
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.CookieContainer = cookieContainer;
            request.ContentLength = postData.Length;

            // 提交请求数据
            System.IO.Stream outputStream = request.GetRequestStream();
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();

            HttpWebResponse response;
            Stream responseStream;
            StreamReader reader;
            string srcString;
            response = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
            srcString = reader.ReadToEnd();
              //返回值赋值
            reader.Close();
            if (IsContain("Successful Import", srcString))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

标签:提交表单

关于我

喜欢简简单单的生活.

记录平凡世界的点滴

-于2010年12月31日

联系我

  • 微信:fishren
  • 邮箱:
    tanlixiao@163.com
  • Address:
    中国最南端的滨海城市
    河西区 解放路 502