How to install User Agent with System.Net.WebRequest in C #

Hi, I am trying to install the User Agent using WebRequest, but unfortunately I only found how to do it using HttpWebRequest, so here is my code and I hope you can help me install 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 tried adding "request.Headers.Add (" user-agent ", _USER_AGENT); but I am getting an error.

+5
c # webrequest
source share
3 answers

Use the UserAgent property on the UserAgent by HttpWebRequest it on the HttpWebRequest .

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

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

+19
source share

If you try to use HttpWebRequest instead of the base WebRequest, then there is a specific property set 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
source share
 WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext"); ((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework" 
0
source share

All Articles