Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set User Agent with System.Net.WebRequest in c#

Tags:

c#

webrequest

I'm trying to set User Agent with WebRequest, but unfortunately, I've only found how to do it using HttpWebRequest, so here is my code and I hope you can help me to set the User-Agent using WebRequest.

here is my code

    public string Post(string url, string Post, string Header, string Value)
    {
        string str_ReturnValue = "";

        WebRequest request = WebRequest.Create(url);

        request.Method = "POST";
        request.ContentType = "application/json;charset=UTF-8";                        
        request.Timeout = 1000000;

        if (Header != null & Value != null)
        {
            request.Headers.Add(Header, Value);                                
        }

        using (Stream s = request.GetRequestStream())
        {
            using (StreamWriter sw = new StreamWriter(s))
                sw.Write(Post);
        }

        using (Stream s = request.GetResponse().GetResponseStream())
        {                
            using (StreamReader sr = new StreamReader(s))
            {
                var jsonData = sr.ReadToEnd();
                str_ReturnValue += jsonData.ToString();
            }
        }

        return str_ReturnValue;
    }

I have tried with adding request.Headers.Add("user-agent", _USER_AGENT); but I receive an error message.

like image 868
enb141 Avatar asked Nov 11 '15 20:11

enb141


People also ask

What is System Net WebRequest?

WebRequest is the abstract base class for . NET's request/response model for accessing data from the Internet.

What is Useragent in HttpWebRequest?

The User Agent is used to identify the client and operating system etc.

What is the difference between HttpWebRequest and WebRequest?

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in . NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest.


1 Answers

Use the UserAgent property on HttpWebRequest by casting it to a HttpWebRequest.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "my user agent";

Alternatively, instead of casting you can use WebRequest.CreateHttp instead.

like image 71
vcsjones Avatar answered Oct 16 '22 21:10

vcsjones