1.WebRequest的发送数据以及接收数据
class Program
{
static void Main(string[] args)
{
//创建一个实例并发送请求
HttpWebRequest we = (HttpWebRequest)WebRequest.Create("http://hao.360.cn/?src=360c");
we.Method = "Get";
we.KeepAlive = true;
//设置返回数据超时的时间30s
we.Timeout = ;
//开始异步获得发过来的数据
we.BeginGetResponse(new AsyncCallback(Callback), we); Console.ReadKey();
} static void Callback(IAsyncResult result)
{
HttpWebRequest we = (HttpWebRequest)result.AsyncState;
//结束获得的数据
WebResponse web = we.EndGetResponse(result);
//读取返回来的数据
using (Stream stream = web.GetResponseStream())
{
StreamReader streamReader = new StreamReader(stream);
string ss = streamReader.ReadToEnd();
Console.Write(ss);
}
}
}
2.HttpWebRequest的使用
class Program
{
static void Main(string[] args)
{
//创建一个请求实例
WebRequest web = (HttpWebRequest)HttpWebRequest.Create("http://www.baidu.com");
web.Method = "Post";
//开始异步发送请求数据
web.BeginGetRequestStream(new AsyncCallback(AsyncCallback), web);
Console.ReadKey();
} //发送数据 可以考虑发送登录的密码以及账号信息等
static void AsyncCallback(IAsyncResult result)
{
HttpWebRequest web = (HttpWebRequest)result.AsyncState;
using (Stream stream = web.EndGetRequestStream(result))
{
byte[] postData = Encoding.UTF8.GetBytes("你好");
stream.Write(postData, , postData.Length);
}
//开始异步接收数据
web.BeginGetResponse(new AsyncCallback(CallbackResponse), web); } //接收服务器返回的数据
static void CallbackResponse(IAsyncResult result)
{
HttpWebRequest web = (HttpWebRequest)result.AsyncState;
//结束返回的请求数据
HttpWebResponse response = (HttpWebResponse)web.EndGetResponse(result);
//输出返回的数据
using (Stream stream = response.GetResponseStream())
{
StreamReader streamReader = new StreamReader(stream);
//Console.WriteLine(streamReader.ReadToEnd()); File.WriteAllText(@"C:/12e.txt", streamReader.ReadToEnd(),Encoding.UTF8);
}
} }