如何从 RestClient 更改为对 API 请求使用 HttpRequestMessage

How to change from RestClient to use HttpRequestMessage for API request

我想从使用 rest RestClient 更改为使用 HttpClient 和 HttpRequestMessage 从我拥有的一些功能,但是,它似乎没有相应地工作,因为它没有连接到服务器。

如何更改RestClient并使用HttpRequestMessage,请参阅下面的代码原始代码和我的代码更改或尝试?

有没有更简单的方法将 RestClient 转换为 HttpRequestMessage?

原创-获取会话

    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;
        }
    }

这就是我尝试使用 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;
        }
    }

您尝试修改方法“GetSession1”中的一些代码:转换后缺少键“params”:

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