C# HttpWebRequest将凭据传递给下一个HttpWebRequest
我正在使用HttpWebRequest登录一个页面并获取一些信息。然后,我使用这些信息创建一个新的HttpWebRequest以获取更多信息。我不想使用WebClient 如何将使用第一个HttpWebRequest登录获得的凭据传递给第二个 编辑:如果我使用CookieCollection,则返回为空。我只是尝试使用WebClient作为最后手段,即使它不起作用,第二个请求也会将我带回登录屏幕。我注意到WebBrowser中有一个cookie。在发送请求之前为每个请求添加一个cookie。将从第一个响应获得的cookie添加到第二个请求。假设他们使用cookies进行身份验证,这应该验证第二个请求C# HttpWebRequest将凭据传递给下一个HttpWebRequest,c#,.net,login,httpwebrequest,credentials,C#,.net,Login,Httpwebrequest,Credentials,我正在使用HttpWebRequest登录一个页面并获取一些信息。然后,我使用这些信息创建一个新的HttpWebRequest以获取更多信息。我不想使用WebClient 如何将使用第一个HttpWebRequest登录获得的凭据传递给第二个 编辑:如果我使用CookieCollection,则返回为空。我只是尝试使用WebClient作为最后手段,即使它不起作用,第二个请求也会将我带回登录屏幕。我注意到WebBrowser中有一个cookie。在发送请求之前为每个请求添加一个cookie。将从
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;
...
这是一个非常古老的问题,我知道它没有声明任何
WebClient
,但我会在这里为所有从谷歌遇到这个问题的人发帖。最初的概念不是我的代码。我不知道我最初在哪里找到的
using (WebClientEx client = new WebClientEx())
{
client.IntTimeout = intTimeout;
client.DownloadString(strReportUrlPrefix + strReportUrlQuery);
NameValueCollection auth = new NameValueCollection
{
{ "j_username", strReportUsername},
{ "j_password", strReportPassword}
};
byte[] data = client.UploadValues(strReportUrlPrefix + "j_security_check", auth);
// LOGIC HERE WITH DATA
}
WebClientEx
Class:
public class WebClientEx : WebClient
{
private CookieContainer _cookieContainer = new CookieContainer();
public int IntTimeout { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request != null)
request.Timeout = IntTimeout;
if (request is HttpWebRequest)
(request as HttpWebRequest).CookieContainer = _cookieContainer;
return request;
}
}
这只是一个基于答案2的示例运行代码。也许是多余的,也许是某个人
string url = "http://servername/place-where-data-is.extension"
string loginUrl = "https://servername/sampleLogin?email=eeeeee&passwd=xxxxxxx";
HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(loginUrl);
loginRequest.CookieContainer = new CookieContainer();
loginRequest.Method = WebRequestMethods.Http.Get;
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
var cookies = new CookieContainer();
cookies.Add(loginResponse.Cookies);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookies;
request.Method = WebRequestMethods.Http.Get;
WebResponse response = (WebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
cookies.Add(response.cookies);实际上也需要一个Uri。我该怎么做呢。cookies.Add(Uri????,response.cookies)@anon-应该有一个接受单个CookieCollection参数的方法:。使用那个。结果是cooky集合是空的。在这种情况下我该怎么办?太好了,我正在基于这个想法添加我的示例代码,我想它可能会说明一些人。