HTTPWebRequest - “访问”页面 - C#

时间:2012-11-22 20:48:58

标签: c# http httpwebrequest

好的,我一直在读qutie很多页面试图找到我的问题的答案,但我没有运气。基本上我想在C#中使用HTTPWebRequest来访问网页。这是我到目前为止所做的,似乎没有用。 Wireshark也不会显示任何返回的cookie。假设我已经宣布了我需要的一切:

private void cmdVisit_Click(object sender, EventArgs e)
    {


        url = textBox1.Text;

        string front = "http://";
        string prx = front + lstProxy.Items[x].ToString();

        WebProxy myProxy = new WebProxy(prx);
        CookieContainer cookieJar = new CookieContainer();
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

       request.Method = "GET";
       request.Proxy = myProxy;
       request.Referer = "http://anyrefererItypehere";
       request.CookieContainer = cookieJar;
       request.ContentType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
       request.KeepAlive = true;
       request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
       request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
       request.Headers.Add(HttpRequestHeader.AcceptLanguage, "Accept-Language: en-us,en;q=0.5");
       request.Host = "anyblogItypehere.tumblr.com";

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

        Stream stream = webResponse.GetResponseStream();
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        String responseString = reader.ReadToEnd();

        webResponse.Close();
        rtbSource.Text = responseString;


        }

1 个答案:

答案 0 :(得分:0)

从网页获取内容的简单方法(为清晰起见,省略了错误处理代码):

 public static string GetContent(string uri)
 {
     using (WebClient client = new WebClient())
     {
         // Pretend to be IE6
         client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
         return client.DownloadString(uri);
      }
  }

如果要指定代理,请使用客户端对象上的Proxy属性。