1

I am using the WebClient class with cookies as mentioned here: Using CookieContainer with WebClient class

What steps are required to add a custom user agent to every request made by this WebClient?

I tried to put the

Headers.Add(HttpRequestHeader.UserAgent, "...") 

line into

protected override WebRequest GetWebRequest

but that did not work: "This header must be modified using the appropriate property".

1
  • were you aware that WebClient is part of .NET and not part of C#? Commented Jun 30, 2010 at 23:49

2 Answers 2

3

from http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx ,

using System;
using System.Net;
using System.IO;

    public class Test
    {
        public static void Main (string[] args)
        {
            if (args == null || args.Length == 0)
            {
                throw new ApplicationException ("Specify the URI of the resource to retrieve.");
            }
            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;)");

            Stream data = client.OpenRead (args[0]);
            StreamReader reader = new StreamReader (data);
            string s = reader.ReadToEnd ();
            Console.WriteLine (s);
            data.Close ();
            reader.Close ();
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Did you know your code was unformatted? Next time, please select it in the editor and press Control-K.
old answer but it just solved my problem in a heartbeat so it deserved an upvote.
0

Kinda late answer but here it goes; I had the same problem as you and solved it by adding a line to the example you linked:

public class CookieAwareWebClient : WebClient
{
    private CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).UserAgent       = "CUSTOM USERAGENT HERE";
            (request as HttpWebRequest).CookieContainer = m_container;
        }
        return request;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.