当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

模拟浏览器请求URL 带Cookie

  private CookieContainer cookieContainer =  = new CookieContainer();

  public string RequestByPost(string url, string postData)

  {

  int num = 3;

  string str = null;

  while (num-- > 0)

  {

  try

  {

  Thread.Sleep((int)(delayTime * 0x3e8));

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

  request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)";

  request.Method = "POST";

  request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";

  request.KeepAlive = true;

  request.ContentType = "application/x-www-form-urlencoded";

  request.CookieContainer = this.cookieContainer;

  //request.Proxy = this.webProxy;

  HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

  request.CachePolicy = policy;

  byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(postData);

  request.ContentLength = bytes.Length;

  Stream requestStream = request.GetRequestStream();

  requestStream.Write(bytes, 0, bytes.Length);

  requestStream.Close();

  HttpWebResponse response = (HttpWebResponse)request.GetResponse();

  StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true);

  str = reader.ReadToEnd();

  response.Close();

  reader.Close();

  return str;

  }

  catch (Exception exception)

  {

  if (exception.Message.IndexOf("内部服务器错误") > 0)

  {

  return "(500)";

  }

  Logging("RequestByPost", exception.Message);

  continue;

  }

  }

  return str;

  }

  public string RequestByGet(string url)

  {

  int num = 3;

  string str = null;

  while (num-- > 0)

  {

  try

  {

  Thread.Sleep((int)(delayTime * 0x3e8));

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

  request.Method = "GET";

  request.CookieContainer = this.cookieContainer;

  HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

  request.CachePolicy = policy;

  HttpWebResponse response = (HttpWebResponse)request.GetResponse();

  StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true);

  str = reader.ReadToEnd();

  response.Close();

  reader.Close();

  return str;

  }

  catch (Exception exception)

  {

  if (exception.Message.IndexOf("内部服务器错误") > 0)

  {

  return "(500)";

  }

  Logging("RequestByGet", exception.Message);

  continue;

  }

  }

  return str;

  }

相关内容
赞助商链接