利用WebRequest来实现模拟浏览器通过Post方式向服务器提交数据

224 篇文章 0 订阅
align="center" marginwidth="0" marginheight="0" src="http://218.16.120.35:65001/PC/Global/images/b.html" frameborder="0" width="728" scrolling="no" height="90">
 

//通过Post发送的数据
   string payload="chkbook=book&keyword=管理";
   WebRequest req = WebRequest.Create("http://localhost/pceo/Search.aspx");
   req.Method = "POST";
   req.ContentType = "application/x-www-form-urlencoded";
   StringBuilder UrlEncoded = new StringBuilder();
   Char[] reserved = {'?', '=', '&'};
   byte[] SomeBytes = null;
   if (payload != null)
   {
    int i=0, j;
    while(i<payload.Length)
    {
     j=payload.IndexOfAny(reserved, i);
     if (j==-1)
     {
      UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, payload.Length-i),System.Text .Encoding .GetEncoding ("gb2312")));
      break;
     }
     UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, j-i),System.Text .Encoding .GetEncoding ("gb2312")));
     UrlEncoded.Append(payload.Substring(j,1));
     i = j+1;
    }
    SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
    req.ContentLength = SomeBytes.Length;
    Stream newStream = req.GetRequestStream();
    newStream.Write(SomeBytes, 0, SomeBytes.Length);
    newStream.Close();
   }
   else
   {
    req.ContentLength = 0;
   }
   try
   {
    WebResponse result = req.GetResponse();
    Stream ReceiveStream = result.GetResponseStream();

    Byte[] read = new Byte[512];
    int bytes = ReceiveStream.Read(read, 0, 512);

    txtHTML.InnerHtml = "";
    while (bytes > 0)
    {

     // 注意:
     // 下面假定响应使用 UTF-8 作为编码方式。
     // 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
     //  Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
     Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
     txtHTML.InnerHtml = txtHTML.InnerHtml + encode.GetString(read, 0, bytes);
     bytes = ReceiveStream.Read(read, 0, 512);
    }
   }
   catch(Exception)
   {
    txtHTML.InnerHtml = "检索页时出错";
   }

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值