How do you login to a webpage and retrieve its content in C#?

前端 未结 7 2035
孤街浪徒
孤街浪徒 2020-12-30 17:13

How do you login to a webpage and retrieve its content in C#?

7条回答
  •  暖寄归人
    2020-12-30 17:39

    You can use the build in WebClient Object instead of crating the request yourself.

    WebClient wc = new WebClient();
    wc.Credentials = new NetworkCredential("username", "password");
    string url = "http://foo.com";          
    try
    {
        using (Stream stream = wc.OpenRead(new Uri(url)))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
                 }
        }
    }
    catch (WebException e)
    {
        //Error handeling
    }
    

提交回复
热议问题