You'll need to use an object that can handle storing cookies. In this case, you'll need the HttpWebRequest
class. You'll also need a CookieContainer
to manage authentication cookies.
To do this you would:
- Create a
CookieContainer
object (a cookie jar) that you can keep track of throughout the scope of every request you make.
- Create an
HttpWebRequest
that logs into the site you're accessing.
- Use the
CookieContainer
you created in step 1 for every subsequent request.
Below is an example of how to use the HttpWebRequest, HttpWebResponse, and CookieContainer classes together to make a simple request that will set some cookies, and then using those cookies on a subsequent request. The rest should be easy assuming everything is well formed markup ;)
CookieContainer cookieJar = new CookieContainer();
var webRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
webRequest.CookieContainer = cookieJar;
var webResponse = webRequest.GetResponse();
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
var anotherWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/search?q=stackoverflow.com");
anotherWebRequest.CookieContainer = cookieJar;
webResponse = anotherWebRequest.GetResponse();
Another option (if you really want to use the WebClient
class) would be to parse out the ResponseHeaders
property of the class once you've made your request and include the appropriate cookies in your next request. This is a little more involved though since it requires you to manage your cookies manually.
Since I'm assuming that you want to be able to traverse your web responses as XML, I suggest you look into the open source library, HtmlAgilityPack. It allows you to send in markup from a web site that is (most likely) not well-formed, or has some sort of invalid markup in it, and then fixes the invalid parts so that you can traverse it like XML.