Home > database >  How can I translate Webrequest method in HttpClient
How can I translate Webrequest method in HttpClient

Time:05-02

I have this code for recovering Http code and description, but Visual Studio says that WebRequest is obsolete and that I have to use HttpClient. I'm not familiar with HttpClient can you help me?

IConfigurationRoot config;

myRequest = WebRequest.CreateHttp($"{config["BASE_URL"]}{link}");
myResponse = (HttpWebResponse)myRequest.GetResponse();
Check_load($"{config["BASE_URL"]}{link}");

var code = ((int)myResponse.StatusCode);  
var desc = myResponse.StatusDescription;

CodePudding user response:

var client = new HttpClient();
var response = await httpClient.GetAsync(url);
var statusCode = response.StatusCode;
var content = response.Content;
if(statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created){
   //return something, error, description
}

CodePudding user response:

The use of HttpClient is very simple. See the code below

        try
        {
            using (HttpClient client = new HttpClient())
            {
                var res = await client.GetAsync(url);
                var response = await res.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<MyObject>(response);
                // use the new data retreived...
            }
        }
        catch (Exception)
        {
            responseMessage = new BadRequestObjectResult("error retreiving data");
        }

This suppose your data are sent in JSON format

  • Related