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
1.1k views
in Technique[技术] by (71.8m points)

http headers - Faking browser request in ASP.net C#

I'm using the code below to pull one of our 3rd party developed pages in so I can parse it as XML for my random bits of work.

Irritatingly we stil have a browser detection level set on the server that only allows certain browsers on to the site; so the question is how would I fake it so that the server thinks its a browser request?

   static string GetHtmlPage(string strURL)
    {

        String strResult;
        System.Net.WebResponse objResponse;

        System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);

        objResponse = objRequest.GetResponse();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
        {
            strResult = sr.ReadToEnd();
            sr.Close();
        }
        return strResult;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Browser detection is done based on a header in the request to the server. All you need to do is set that header. However, with HttpWebRequest you don't set that through the headers collection but rather with the .UserAgent property.

...
System.Net.WebRequest objRequest = 
   System.Net.HttpWebRequest.Create(strURL);

//Pretend to be IE7
((System.Net.HttpWebRequest)objRequest).UserAgent = 
   "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";

objResponse = objRequest.GetResponse();
...

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

...