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

前端 未结 3 1010
遇见更好的自我
遇见更好的自我 2020-12-31 11:15

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

相关标签:
3条回答
  • 2020-12-31 11:41

    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.

    0 讨论(0)
  • 2020-12-31 11:42

    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();
    
    0 讨论(0)
  • 2020-12-31 11:50
    WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext");
    ((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework"
    
    0 讨论(0)
提交回复
热议问题