HttpWebRequest返回值不同于浏览器,可能是一个cookie

本文关键字:cookie 一个 不同于 返回值 浏览器 HttpWebRequest | 更新日期: 2023-09-27 18:12:01

尝试在线访问XML,使用HttpWebRequest和以下代码:

HttpWebRequest webRequest = HttpWebRequest.Create("http://example.com/example.xml") as HttpWebRequest;
webRequest.CookieContainer = new CookieContainer();
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.ASCII);
string data = sr.ReadToEnd();

当我浏览URL时,可以看到XML,但是变量数据包含以下内容:

<html><body><script>document.cookie='lllllll=e0b70895lllllll_e0b70895; path=/';window.location.href=window.location.href;</script></body></html>

我检查了webResponse。Cookies但是它是空的

我怎么能得到过去这使用webrequest和xml进入数据变量?

HttpWebRequest返回值不同于浏览器,可能是一个cookie

你写的都是对的。问题是在您的情况下(但这是一个很好的解决方案,对机器人),cookie添加的Javascript,而不是在HTTP响应。

document.cookie='lllllll=e0b70895lllllll_e0b70895; path=/'

这行JavaScript代码设置cookie。所以它需要在这个响应之后的代码中设置。您可以使用CookieContainer.Add()方法轻松地做到这一点。

window.location.href=window.location.href

这行代码只是刷新页面,但如果在浏览器中cookie已经设置,这就是为什么你可以得到响应。

要得到这个cookie,你需要使用regex,因为我认为cookie的名字也是动态的。

所以你需要添加这样的内容:

// Catch the cookie name and value with using regex, than remove the
// characters what we only need for the regex match.
string cookieName = Regex.Match(data, "'[a-z]*").Value.Remove(0, 1);
string cookieValue = Regex.Match(data, "=[a-zA-Z0-9]*").Value.Remove(0, 1);
webRequest.CookieContainer.Add(new Cookie(cookieName,cookieValue));
webResponse = webRequest.GetResponse() as HttpWebResponse;
StreamReader sr2 = new StreamReader(webResponse.GetResponseStream(), Encoding.ASCII);
string data = sr2.ReadToEnd();