[英]HttpWebRequest return value different from brower, maybe a cookie
尝试使用HttpWebRequest和以下代码在线访问XML:
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放入data变量中?
你写的一切都是正确的。 问题出在您的情况下(但这是针对机器人的一个很好的解决方案),它是Javascript添加的cookie,而不是HTTP响应中的cookie。
document.cookie='lllllll=e0b70895lllllll_e0b70895; path=/'
此行JavaScript代码设置cookie。 因此,需要在此响应后在代码中进行设置。 您可以使用CookieContainer.Add()
方法轻松地做到这一点。
window.location.href=window.location.href
这行代码只是刷新页面,但是如果已经在浏览器中设置了cookie,这就是为什么您可以获得响应的原因。
要获得此cookie,您需要使用正则表达式,因为我认为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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.