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

发布于 2025-01-10 03:41:18 字数 2608 浏览 0 评论 0原文

我想从使用 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;
        }
    }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我一向站在原地 2025-01-17 03:41:18

您尝试修改方法“GetSession1”中的一些代码:转换后丢失了关键“params”:

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

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 + "\"}")                   
            };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文