How do you login to a webpage and retrieve its con

2019-02-05 15:24发布

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

7条回答
姐就是有狂的资本
2楼-- · 2019-02-05 15:41

How do you mean "login"?

If the subfolder is protected on the OS level, and the browser pops of a login dialog when you go there, you will need to set the Credentials property on the HttpWebRequest.

If the website has it's own cookie-based membership/login system, you will have to use HttpWebRequest to first response to the login form.

查看更多
beautiful°
3楼-- · 2019-02-05 15:49

Use the WebClient class.

Dim Html As String

Using Client As New System.Net.WebClient()
    Html = Client.DownloadString("http://www.google.com")
End Using
查看更多
Emotional °昔
4楼-- · 2019-02-05 16:00
string postData = "userid=ducon";
            postData += "&username=camarche" ;
            byte[] data = Encoding.ASCII.GetBytes(postData);
            WebRequest req = WebRequest.Create(
                URL);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            Stream newStream = req.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
            string coco = reader.ReadToEnd();
查看更多
淡お忘
5楼-- · 2019-02-05 16:02

That depends on what's required to log in. You could use a webclient to send the login credentials to the server's login page (via whatever method is required, GET or POST), but that wouldn't persist a cookie. There is a way to get a webclient to handle cookies, so you could just POST the login info to the server, then request the page you want with the same webclient, then do whatever you want with the page.

查看更多
SAY GOODBYE
6楼-- · 2019-02-05 16:06

Look at System.Net.WebClient, or for more advanced requirements System.Net.HttpWebRequest/System.Net.HttpWebResponse.

As for actually applying these: you'll have to study the html source of each page you want to scrape in order to learn exactly what Http requests it's expecting.

查看更多
Summer. ? 凉城
7楼-- · 2019-02-05 16:06

Try this:

public string GetContent(string url)  
{ 
  using (System.Net.WebClient client =new System.Net.WebClient()) 
  { 
  return client.DownloadString(url); 
  } 
} 
查看更多
登录 后发表回答