首页 > 开发 > 综合 > 正文

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

2024-07-21 02:29:19
字体:
来源:转载
供稿:网友
 

//通过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 = "检索页时出错";
   }

出处:狂风之家 blog

,欢迎访问网页设计爱好者web开发。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表