我正在尝试检索一个网页的源代码,我使用HTTPWebRequest,但只有这是返回:
<script type="text/javascript">
window.location="index.php";
</script>
我使用fiddler获得chrome获得网页的比较,并将其与我的代码检索进行比较。
Chrome在左边VS code在右边
https://i.stack.imgur.com/Hgk9w.png我注意到的是,内容长度不像chrome得到的那么大。我的代码内容长度通常在70个字节左右,而chrome通常返回87000个字节。
我试过使用流和内存流。有人能给我指个正确的方向吗?
下面是我的函数:public string GetAllCampaings()
{
string campaigns = null;
byte[] result;
byte[] buffer = new byte[4096];
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://magiclampmarketing.com/sms/manage_groups.php");
httpWebRequest2.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
httpWebRequest2.Method = "GET";
httpWebRequest2.CookieContainer = cookieContainer;
httpWebRequest2.KeepAlive = true;
httpWebRequest2.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
httpWebRequest2.Referer = "http://magiclampmarketing.com/sms/main.php";
httpWebRequest2.SendChunked = false;
WebHeaderCollection myWebHeaderCollection = httpWebRequest2.Headers;
myWebHeaderCollection.Add("Accept-Language", "en;q=0.8");
myWebHeaderCollection.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
myWebHeaderCollection.Add("Accept-Encoding", "gzip,deflate,sdch");
var sp = httpWebRequest2.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);
using (WebResponse response = httpWebRequest2.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
int count = 0;
do
{
count = responseStream.Read(buffer, 0, count);
memoryStream.Write(buffer, 0, count);
} while (count != 0);
result = memoryStream.ToArray();
}
}
}
return campaigns;
}
看起来你正在使用的chrome浏览器已经登录到该网站,并有一个会话cookie。但是,您的代码没有突出显示如何传递会话cookie。
从所看到的情况来看,看起来来自程序的请求返回了一个响应,该响应将您重定向到登录页面。
你要么必须澄清你传递会话cookie的方式。或者接受你的程序正在做它应该做的事情。