|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace CSharp_WinForm_WebBrowser_登录百度
{
public partial class Form1 : Form
{
//非静态的不能直接使用,要新建一个对象来调用
CookieContainer cc = new CookieContainer();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
#region 账号密码POST进去
//账号密码POST进去
string BAIDU_Url = "http://passport.baidu.com/?login";
//请求网页
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BAIDU_Url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = false;
//把账号密码登录
byte[] postData = System.Text.Encoding.Default.GetBytes("username=" + this.textBox1.Text + "&password=" + this.textBox2.Text + "&men_pass=");
req.ContentLength = postData.Length;
req.CookieContainer = cc;
using (Stream sm = req.GetRequestStream())//请求的数据流
{
sm.Write(postData, 0, postData.Length);
}
#endregion
string strResult;//定义一个字符串来得到读出数据的值
//回应网页,资源来自网页中
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
res.Cookies = cc.GetCookies(req.RequestUri);//获取Cookies实例
using (Stream smRes = res.GetResponseStream())//用来获取从服务器中的数据流
{
using (StreamReader sr = new StreamReader(smRes, System.Text.Encoding.Default))
{
strResult = sr.ReadToEnd();
}
}
res.Close();
req = (HttpWebRequest)WebRequest.Create(" http://zhidao.baidu.com/q?ct=17&rn=25&lm=393738&tn=ikpsask2");
req.CookieContainer = cc;
res = (HttpWebResponse)req.GetResponse();
using (Stream smRes = res.GetResponseStream())
{
using (StreamReader sr = new StreamReader(smRes, System.Text.Encoding.Default))
{
strResult = sr.ReadToEnd();
}
}
res.Close();
string filename = Path.GetTempFileName();
using (StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.Default))
{
sw.Write(strResult);
}
this.webBrowser1.Navigate("file://"+filename);
}
}
}
其中:req = (HttpWebRequest)WebRequest.Create(" http://zhidao.baidu.com/q?ct=17&rn=25&lm=393738&tn=ikpsask2");
create后面的参数是什么?为什么我加上那个会出现网站访问错误
|
|