zoukankan      html  css  js  c++  java
  • C#通过POST发送数据函数,类似asp中的xmlhttp

     1 //purl处理页面,str参数(如:username=admin&passwod=123456)
     2 
     3 //返回处理页面输出的内容
     4 
     5 //使用:string data = PostData("http://www.zhangxun.net/", "action=Fav&str=这个是好网站");
     6 
     7        public static string PostData(string purl,string str)
     8         {
     9             try
    10             {
    11                 byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
    12                 // 准备请求 
    13                 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(purl);
    14 
    15                 //设置超时
    16                 req.Timeout = 30000;
    17                 req.Method = "Post";
    18                 req.ContentType = "application/x-www-form-urlencoded";
    19                 req.ContentLength = data.Length;
    20                 Stream stream = req.GetRequestStream();
    21                 // 发送数据 
    22                 stream.Write(data, 0, data.Length);
    23                 stream.Close();
    24 
    25                 HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
    26                 Stream receiveStream = rep.GetResponseStream();
    27                 Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
    28                 // Pipes the stream to a higher level stream reader with the required encoding format. 
    29                 StreamReader readStream = new StreamReader(receiveStream, encode);
    30 
    31                 Char[] read = new Char[256];
    32                 int count = readStream.Read(read, 0256);
    33                 StringBuilder sb = new StringBuilder("");
    34                 while (count > 0)
    35                 {
    36                     String readstr = new String(read, 0, count);
    37                     sb.Append(readstr);
    38                     count = readStream.Read(read, 0256);
    39                 }
    40 
    41                 rep.Close();
    42                 readStream.Close();
    43 
    44                 return sb.ToString();
    45 
    46             }
    47             catch (Exception ex)
    48             {
    49                 return "";
    50                // ForumExceptions.Log(ex);
    51             }
    52         }
    53 
    54 
  • 相关阅读:
    好久没来园子里转了,最近在学ssh,有个小问题提出来
    ClearType使用的问题
    Metro中访问特定设备的方法
    UMDF驱动程序快速上手
    关于GPS使用上的一个怪异问题
    一个不能创建WINCE6.0工程的问题
    Metro开发小记
    在WINPE中添加驱动
    DOS命令活用
    METRO开发中的多语言处理
  • 原文地址:https://www.cnblogs.com/xxaxx/p/1604447.html
Copyright © 2011-2022 走看看