C# connecting to web page with authentication
So I've been trying to fetch a web page that uses authentication to a string and save it to a file. It should be pretty basic so I hope someone can see my errors. I'm very new to C# so treat me thereafter :)
This code functions to some extend, but the file I get is the html for the login screen and not the page that its shown for users that is logged in. What is it I'm doing wrong?
using Syste开发者_StackOverflow社区m;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace fetchingweb
{
class WebAutheticator
{
static void Main(string[] args)
{
string htmlHer = GetWeb();
StreamWriter file = new
StreamWriter("C:\\Users\\user\\Documents\\atextfile.txt");
file.Write(htmlHer);
file.Close();
} //main end
private static string GetWeb()
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("user", "pass");
string url = "http://someurl.com/index.php";
try
{
using (Stream stream = wc.OpenRead(new Uri(url)))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (WebException e)
{
return "failure!";
}
} //getweb end
} //class end
} //namespace end
You are using NetworkCredential to login at the webapp, but the webapp is using some kind of forms authentication. As long as the webapp is not configured to use network credentials this will not work.
Since this is a php application I guess it uses plain forms auth and that you will need to post username/password to the login page before continuing.
Look at the code on the login page of the site you're trying to log into and download.
There will be a <FORM..>
section, if its post you need to post, if its get you use get. It will either post to a new page, and possibly use redirection, or, even refer to itself. Chances are it will use either some form of session id, or cookies to prove you logged in.
Best way to understand this is to write a proxy, which takes your requests, and shows what you send and what you get back.. As this is the best way to understand what happens when you use things and what your program would need to do to mimic it
精彩评论