Browser Impersonation

Sometimes it is necessary to impersonate a certain browser type. For example, some sites only allow certain types of browsers (e.g. IE, Firefox, etc.) and would consider other less commonly used browsers (e.g. Konqueror) as “not supported”. It is thus often useful for the code to impersonate as a different type of browser.

As it turns out, browser impersonation can be done very easily using .Net. The following code illustrates how this is done in C#:

HttpWebRequest r = (HttpWebRequest)WebRequest.Create("{url}");

r.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)";

WebResponse wResponse = r.GetResponse();

Stream rStream = wResponse.GetResponseStream();

StreamReader reader = new StreamReader(rStream, Encoding.ASCII); string respHTML = reader.ReadToEnd();

The key is to set the UserAgent property of the HttpWebRequest object according to the type of browser that the code intends to impersonate. In the example given above, we were trying to impersonate IE7.

To impersonate Firefox 2.0, change the UserAgent to “Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1” instead.

UserAgent value can be obtained from the HttpRequest object. Or you can go to http://www.kerrywong.com/httpreq/ to find out.

Be Sociable, Share!

Leave a Reply