c# – 使用WebClient或WebRequest登录到网站并访问数据

前端之家收集整理的这篇文章主要介绍了c# – 使用WebClient或WebRequest登录到网站并访问数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用WebClient / WebRequest访问网站上的受限数据.该网站没有官方的API,所以我想要做的只是填写 HTML表单并将值发布到服务器,以便我登录.

我试过thisthis,但看起来不像即将到来的请求被登录.

后一个例子更具吸引力,因为我显然更喜欢WebClient,但遗留的WebRequest将会做.

无论如何,在第一个例子中,我认为它已经登录,但访问私有数据的即将到来的请求返回一个包含消息“这只是成员内容”的页面.

如何使WebClient永久登录

解决方法

这是我做的,它的作品( credit).

添加这个类:

namespace System.Net
{
  using System.Text;
  using System.Collections.Specialized;

  public class CookieAwareWebClient : WebClient
  {
    public void Login(string loginPageAddress,NameValueCollection loginData)
    {
      CookieContainer container;

      var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
      request.ContentLength = buffer.Length;
      var requestStream = request.GetRequestStream();
      requestStream.Write(buffer,buffer.Length);
      requestStream.Close();

      container = request.CookieContainer = new CookieContainer();

      var response = request.GetResponse();
      response.Close();
      CookieContainer = container;
    }

    public CookieAwareWebClient(CookieContainer container)
    {
      CookieContainer = container;
    }

    public CookieAwareWebClient()
      : this(new CookieContainer())
    { }

    public CookieContainer CookieContainer { get; private set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
      var request = (HttpWebRequest)base.GetWebRequest(address);
      request.CookieContainer = CookieContainer;
      return request;
    }
  }
}

用法

public static void Main()
{
  var loginAddress = "www.mywebsite.com/login";
  var loginData = new NameValueCollection
    {
      { "username","shimmy" },{ "password","mypassword" }
    };

  var client = new CookieAwareWebClient();
  client.Login(loginAddress,loginData);
}
原文链接:https://www.f2er.com/csharp/92553.html

猜你在找的C#相关文章