Home > Blockchain >  How to change from RestClient to use HttpRequestMessage for API request
How to change from RestClient to use HttpRequestMessage for API request

Time:02-24

I want to change from using rest RestClient to using HttpClient and HttpRequestMessage from a few of the functions that I have, however, it seems to be not working accordingly as it doesn't connect to the server.

How can I change RestClient and use HttpRequestMessage, see the below code original code and my code changes or attempts?

Is there any easier way of converting RestClient to HttpRequestMessage?

Original-Getting the session

    public AuthInfo GetSession()
    {
        try
        {
            ServicePointManager.ServerCertificateValidationCallback  = (sender, certificate, chain, sslPolicyErrors) => true;
            string url = string.Format("{0}xxx/xxx/xxx?xxx", _client._Url);
            var client = new RestClient(url)
            {
                Timeout = -1
            };
            var request = new RestRequest(Method.POST).AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("params", "{\"login\":\""  _client._Login   "\",\"password\":\""   _client._Password   "\"}");
            var response = client.Execute(request);
            return JsonConvert.DeserializeObject<AuthInfo>(response.Content);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

This is how am trying to get sessions using HttpRequestMessage

    public async Task<AuthInfo> GetSession1()
    {
        string jsonString = string.Empty;
        try
        {
            BaseRateMonitorSettings settings = GetAppSettings();
            ServicePointManager.ServerCertificateValidationCallback  = (sender, certificate, chain, sslPolicyErrors) => true;
            string url = string.Format("{0}xxx/xxx/xxx?xxx", settings.Url);

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var values = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("login", settings.Login),
                new KeyValuePair<string, string>("password", settings.Password)
            };

            HttpResponseMessage response = await client.PostAsync(url, new FormUrlEncodedContent(values));
            //removing extra charactors
            jsonString  = response.Content.ReadAsStringAsync().Result.Replace("\\", "").Trim(new char[1] { '"' });
            var data = JsonConvert.DeserializeObject<AuthInfo>(jsonString);
            client.Dispose();
            return data;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

CodePudding user response:

you try modifying some codes in method "GetSession1": key "params" was missed after converting:

var values = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("params", "{\"login\":\""  settings.Login   "\",\"password\":\""   settings.Password   "\"}")                   
            };
  • Related