3

C# で Web ページにログインしてそのコンテンツを取得するにはどうすればよいですか?

4

7 に答える 7

5

それは、ログインに必要なものによって異なります。Web クライアントを使用して、ログイン資格情報をサーバーのログイン ページに送信できます (GET または POST のいずれかの方法が必要です)。Cookie を処理する Web クライアントを取得する方法があるため、ログイン情報をサーバーに POST し、同じ Web クライアントで必要なページを要求し、そのページで必要なことを行うことができます。

于 2009-03-04T15:37:15.850 に答える
3

System.Net.WebClientまたはより高度な要件については、 を参照してくださいSystem.Net.HttpWebRequest/System.Net.HttpWebResponse

これらを実際に適用する場合: スクレイピングする各ページの html ソースを調べて、期待されている Http リクエストを正確に把握する必要があります。

于 2009-03-04T15:36:11.640 に答える
2
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();
于 2009-03-06T19:30:01.720 に答える
2

「ログイン」とは?

サブフォルダーが OS レベルで保護されていて、そこに移動したときにブラウザーがログイン ダイアログを表示する場合は、HttpWebRequest で Credentials プロパティを設定する必要があります。

Web サイトに独自の Cookie ベースのメンバーシップ/ログイン システムがある場合、HttpWebRequest を使用してログイン フォームに最初に応答する必要があります。

于 2009-03-04T15:39:27.967 に答える
1

リクエストを自分で作成する代わりに、WebClient オブジェクトでビルドを使用できます。

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
}
于 2009-03-05T23:58:41.287 に答える
1

WebClientクラスを使用します。

Dim Html As String

Using Client As New System.Net.WebClient()
    Html = Client.DownloadString("http://www.google.com")
End Using
于 2009-03-04T15:38:03.757 に答える
-2

これを試して:

public string GetContent(string url)  
{ 
  using (System.Net.WebClient client =new System.Net.WebClient()) 
  { 
  return client.DownloadString(url); 
  } 
} 
于 2009-03-04T15:46:00.650 に答える