Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

c# - HttpWebRequest pass credentials to next HttpWebRequest

I am logging into a page using HttpWebRequest and getting some information. I then use that information to create a new HttpWebRequest to get some more information. I do not want to use WebClient.

How can I pass the credentials I obtained from logging in using the first HttpWebRequest to the second one?

EDIT: If I use a CookieCollection then this is coming back as empty. I just tried using WebClient as a last resort and even for that it is not working, the second request takes me back to the login screen. I noticed that in a WebBrowser there is a cookie.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add a CookieContainer to each request before you send it. Add the cookies you get from the first response to the second request. Assuming they use cookies for authentication, this should authenticate the second request.

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlWithParameters);
 request.CookieContainer = new CookieContainer();

 HttpWebResponse response = (HttpWebResponse) request.GetResponse();

 var cookies = new CookieContainer();
 cookies.Add( response.Cookies );

 request = (HttpWebRequest)WebRequest.Create(secondUrlWithParameters);
 request.CookieContainer = cookies;

 ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...