Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 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 Reply

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;

 ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...