C#.NET网络编程POST数据到网站

本文介绍了一款简易投票软件的设计与实现过程,该软件通过POST请求更新服务器上的投票计数。文章详细展示了使用C#进行HTTP POST请求的具体代码,并介绍了如何通过正则表达式验证返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天制作了一个投票软件,主要是POST指定数据到指定页面来使后台的票数计算自动增加。
下面我就把我的代码贴出来。为了安全,我隐藏了所有相关的真实网址。

下面首先是命名空间的引用:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;//访问数据流,网页回传的都先是数据流
using System.Text;
using System.Text.RegularExpressions;//正则表达式用来验证回传的网页是否包含目标数据
using System.Windows.Forms;
using System.Net;//必须,对网页的访问通过这个命名空间来实现的

接着是一个函数来实现,为了安全,隐藏了敏感数据(使用星号) 

public Boolean VoteOnce()
    {
      
//创建HttpWebRequest发送请求用
      HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create("http://www.***.com/***/***.asp?***=***&***=***");
      
//下面是相关数据头和数据发送方法
      hwrq.Accept = "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
      hwrq.Referer 
= "http://www.***.com/***/***.asp?***=***&***=***";
      hwrq.ContentType 
= "application/x-www-form-urlencoded";
      hwrq.UserAgent 
= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; MAXTHON 2.0)";
      hwrq.KeepAlive 
= true;
      hwrq.Method 
= "POST";
      
//下面发送数据,使用MiniSniffer来抓包分析应该发送什么数据
      string PostStr = "*=****%**&****=*";
      ASCIIEncoding ASC2E 
= new ASCIIEncoding();
      
byte[] bytePost = ASC2E.GetBytes(PostStr);//把要发送的数据变成字节
      hwrq.ContentLength = bytePost.Length;
      
//下面是发送数据的字节流
      Stream MyStream = hwrq.GetRequestStream();
      MyStream.Write(bytePost, 
0, bytePost.Length);
      MyStream.Close();
//记得要结束字节流啊
      
//创建HttpWebResponse实例
      HttpWebResponse hwrp = (HttpWebResponse)hwrq.GetResponse();
      StreamReader MyStreamR 
= new StreamReader(hwrp.GetResponseStream(), Encoding.Default);
      
string result = MyStreamR.ReadToEnd();
      Boolean r
=false;
      
if (Regex.IsMatch(result, "成功")==true)
      {
        r 
= true;
      }
      MyStreamR.Close();
      
return r;
    }

align="middle" marginwidth="0" marginheight="0" src="http://l.thec.cn/lynnlin/googleContent728x90.htm" frameborder="0" width="650" scrolling="no" height="90">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值