including login credentials with a WebRequest

2019-02-15 10:24发布

问题:

I am trying to "behind the scenes" log myself into a website, from the VB code behind my ASP.NET website. But I am dumbfounded as to how to do this.

As far as I know I should be using the WebRequest or Webclient class. That is about as much as I know. I am not sure how to use the class.

I want to click a button on my website and have its Click event send a username and password to another website. This other site isot affiliated with mine. I realize the concept may seem stupid, but I plan on taking this further later, but Just need to know this now.

If anyone could give me some code example with explanation or direct me to a good tutorial that would be greatly appreciated!

If it helps at all, the website I am trying to log into is www.Lockerz.com

Thanks!

回答1:

If the client site uses basic authentication you can add credentials like this:

WebRequest myReq = WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));   
myReq.Credentials = mycache;

If it uses form login, you can use Fiddler to sniff the data posted on a login, and perform the same request from a HttpWebRequest object. You might want to handle cookies as well if you have to perform multiple requests with the logged in user.

Reference:

  • Cookies: Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse
  • Cookies and POST: HttpWebRequest POST and Cookies
  • Download class: Characters in string changed after downloading HTML from the internet