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

久未见 提交于 2019-11-29 18:04:45

问题


Hi 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.


回答1:


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.




回答2:


If you try using a HttpWebRequest instead of a basic WebRequest, then there is a specific property exposed for UserAgent.

// Create a new 'HttpWebRequest' object to the mentioned URL.
var myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.UserAgent=".NET Framework Test Client";

// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
var myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();



回答3:


WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext");
((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework"


来源:https://stackoverflow.com/questions/33659663/how-to-set-user-agent-with-system-net-webrequest-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!