Setting the User-Agent Header for a Webclient Request

Setting the User-Agent header for a WebClient request

You can check the WebClient documentation for a C# sample that adds a User-Agent to your WebClient and here for a sample for Windows Phone.

This is the sample for C#:

WebClient client = new WebClient ();

// Add a user agent header in case the
// requested URI contains a query.

client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +
"Windows NT 5.2; .NET CLR 1.0.3705;)");

This is a sample for Windows Phone (Silverlight):

request.Headers["UserAgent"] = "appname";
// OR
request.UserAgent = "appname";

How to set User-Agent in WebClient

You can use this code

using (WebClient web = new WebClient())
{
web.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
}

Default User Agent (WebClient Header)

You can indeed just grab one from your favourite browser, or pick one from here.

The user agent string is just that - a string containing various info about the browser. So it's just a matter of passing it along with you request. If your program will live for a while, I'd try to pick one that's as generic as possible.

Set user-agent header during HTTP CONNECT over SSL?

You will not be able to send the User-Agent header using the HttpWebRequest family of classes. The RFCs say that the header is optional (SHOULD rather than MUST)

You could add a rule to the proxy to allow connections out with no User-Agent header, or for particular target servers, or finally code your own HTTP Protocol using the .NET Socket Classes.

How do I set a default User Agent on an HttpClient?

You can solve this easily using:

HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("User-Agent", "C# App");


Related Topics



Leave a reply



Submit