使用Web客户端或WebRequest的登录到网站和访问数据 [英] Using WebClient or WebRequest to login to a website and access data
问题描述
我试图访问使用网站 Web客户端
/ 的WebRequest
上受限的数据。有一个在该网站没有官方的API,所以我想要做的仅仅是填写HTML表单,并张贴值到服务器,所以我登录。
I'm trying to access restricted data on a website using WebClient
/WebRequest
. There is no official API in that website, so what I'm trying to do is simply fill the HTML form and post the values to the server, so I'm logged in.
I tried this and this, but it doesn't look like the upcoming requests are logged in.
后者的例子是,因为我显然preFER Web客户端
,但遗留的WebRequest
会做更吸引人
The latter example is much more appealing since I obviously prefer WebClient
, but legacy WebRequest
will do.
总之,在第一个例子,我认为它没有登录,但访问私人数据即将到来的请求将返回页面一条消息这是会员只有内容。
Anyway, in the first example I think it did login, but the upcoming requests that access the private data return a page with a message "This is member only content".
如何让 Web客户端
在永久登录?
推荐答案
下面是我没有和它的工作原理(信贷)。
Here's what I did and it works (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, 0, 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);
}
这篇关于使用Web客户端或WebRequest的登录到网站和访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!