views:

323

answers:

1

I'm looking for a way to work with an API which requires login, and then redirects to another URL.
The thing is that so far I've only come up with a way to make 2 Http Requests for each action I want to do: first, get cookie with AllowRedirect=false, then get the actual URI and do a second request with the cookie:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

string redirectedUrl = response.Headers["Location"];
if (!String.IsNullOrEmpty(redirectedUrl))
{
    redirectedUrl = "http://www.ApiUrlComesHere.com/" + redirectedUrl;
    HttpWebRequest authenticatedRequest = (HttpWebRequest)WebRequest.Create(redirectedUrl);
    authenticatedRequest.Headers["Cookie"] = response.Headers["Set-Cookie"];        
    response = (HttpWebResponse)request.GetResponse();
}

It seems terribly inefficient. Is there another way?
Thanks!

A: 

It seems terribly inefficient.

Why?

In the end this is all HttpWebRequest, with AllowAutoRedirect true is going to do.

Richard
OK, and code-wise, isn't there a better way to implement this?
Nir
@Nir: not particularly (since you are not setting anything else for the original request).
Richard