using System;
using System.Drawing;
using System.IO;
using
System.Net;
using System.Text;
using System.Windows.Forms;
namespace 用POST提交带验证码的网站
{
public partial class FrmMain :
Form
{
public FrmMain()
{
InitializeComponent();
}
//用于保存cookie
CookieContainer cc =
new CookieContainer();
//获取cookie
private void GetCookie()
{
try
{
//要post提交的地址。先用HttpWebRequest进行请求以得到cookie,并保存起来在后面获取验证码的时候使用
Uri uri = new
Uri("http://61.142.253.40:8085/Login.aspx");
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
//将当前cookie存储到CookieContainer中
cc.Add(response.Cookies);
response.Close();
}
catch { }
}
//读取验证码图片
private void
GetImage()
{
try
{
//验证码地址
Uri uri = new
Uri("http://61.142.253.40:8085/CheckCode.aspx");
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(uri);
//设置前面请求时保存下来的cookie,以保证两个请求是相同的,才不会出现验证码不同步的问题
request.CookieContainer = cc;
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
//得到验证码数据流
Stream resStream = response.GetResponseStream();
//初始化Bitmap图片并在pictureBox1控件中显示
Bitmap image = new Bitmap(resStream);
this.pictureBox1.Image = image;
}
catch { }
}
/// <summary>
///
提交数据
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <param name="code">验证码</param>
/// <returns>提交数据后的返回值</returns>
private string SubmitData(string userName, string
passWord, string code)
{
try
{
string url =
string.Format("http://61.142.253.40:8085/Ajax.aspx?action=Login&Name={0}&Password={1}&ucode={2}",
userName, passWord, code);
HttpWebRequest request = WebRequest.Create(url) as
HttpWebRequest;
//设置cookie,保证请求同步
request.CookieContainer = cc;
//获取响应
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode ==
HttpStatusCode.OK)
{
//注意这里要根据网站编码格式变换
using (StreamReader sr = new
StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")))
{
return sr.ReadToEnd();
}
}
else
{
return
response.StatusCode.ToString();
}
}
catch
{
return
null;
}
}
private void
Form1_Load(object sender, EventArgs e)
{
}
private void
btnSubmit_Click(object sender, EventArgs e)
{
txtResult.Text =
SubmitData(txtUser.Text, txtPassword.Text, txtCode.Text);
}
private void
lbWebSite_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start("http://www.weixq.cn");
System.Diagnostics.Process.Start("http://www.jfkjw.com");
}
catch { }
}
private void lbQQ_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start("http://wpa.qq.com/msgrd?v=3&uin=240452625&site=qq&menu=yes");
}
catch { }
}
private void btnRefresh_Click(object sender, EventArgs e)
{
FrmMain_Load(null, null);
}
private void FrmMain_Load(object sender, EventArgs e)
{
//获取cookie和验证码图片
GetCookie();
GetImage();
}
}
}