C# 实现向Web网站Post数据

来源:互联网 发布:zepto.js 中文手册 编辑:程序博客网 时间:2024/05/21 09:50
以下是一段通过ip138站点的请求,以查询手机归属地的代码:

  1.            string postData = "mobile=13824162584&action=mobile";
  2.             byte[] bs = Encoding.ASCII.GetBytes(postData);
  3.             WebRequest req = WebRequest.Create("http://www.ip138.com:8080/search.asp");
  4.             req.Method = "POST";
  5.             req.ContentType = "application/x-www-form-urlencoded";
  6.             req.ContentLength = bs.Length;
  7.            
  8.             using (Stream reqStream = req.GetRequestStream())
  9.             {
  10.                 reqStream.Write(bs, 0, bs.Length);
  11.             }
  12.             
  13.             using (WebResponse wr = req.GetResponse())
  14.             {
  15.                 //在这里对接收到的页面内容进行处理
  16.                 Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
  17.                 string tempStr = "";
  18.                 string sb = "";
  19.                 Stream receviceStream = wr.GetResponseStream();
  20.                 while(true)
  21.                 {
  22.                     byte[] read = new byte[1024];
  23.                     int iBytes = receviceStream.Read(read, 0, read.Length);
  24.                     if (0 == iBytes)
  25.                     {
  26.                         break;
  27.                     }
  28.                     if (iBytes < read.Length)
  29.                     {
  30.                         byte[] buf = new byte[iBytes];
  31.                         for (int i = 0; i < iBytes; i++)
  32.                         {
  33.                             buf[i] = read[i];
  34.                         }
  35.                         tempStr = encode.GetString(buf);
  36.                         sb += tempStr;
  37.                     }
  38.                     else
  39.                     {
  40.                         tempStr = encode.GetString(read);
  41.                         sb += tempStr;
  42.                     }
  43.                 }
  44.             }



原创粉丝点击