Thursday, October 22, 2009

URI might change in HttpWebResponse

In the following example the red bold line is very important, hence it's red and bold.
Without it, any cookies stored in the CookieContainer object from the GET request might not pass to the POST request. Consider the following scenario:
1. GET request to: "http://site.com/form.php"
2. Request is redirected to: "http://www.site.com/form.php"
3. Cookies are stored for this address
4. POST request to: "http://site.com/form.php"
Clearly, the POST request will not have the cookies. Solution:

CookieContainer cookieContainer = new CookieContainer();
Uri uri = new Uri("http://site.com/form.php");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "GET";
httpWebRequest.CookieContainer = cookieContainer;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
uri = httpWebResponse.ResponseUri;
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Method = "POST";
...


No comments:

Post a Comment