首页 > 解决方案 > Httpclient 性能慢 同一台电脑 Android Emulator Xamarin

问题描述

我正在使用 HttpClient,但我的结果需要 6 秒才能从同一子网中的同一台机器和 192.168 的 IP 范围返回。当我直接从 IP 地址调用 api 时,结果或多或少是即时的,那么为什么在同一台计算机上使用 httpclient 会这么慢。

我已经看到其他建议设置为使用代理的建议,因为 false 是最好的方法。

我还在一部普通手机上对此进行了测试,在手机上成功登录大约需要 8 秒。

private HttpClient _client;
public async Task<String> Getusers()
{
        var content = "";
        HttpClientHandler hch = new HttpClientHandler();
        hch.Proxy = null;
        hch.UseProxy = false;
        _client = new HttpClient(hch);
        var uri = new Uri(Constants.ApiEndPoint + "/Users"); // Your url is here

        try
        {
            var response = await _client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                content = await response.Content.ReadAsStringAsync();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return content;
}

这是我的登录方法,以防任何人看到它有问题。

private async void BtnLogin_Clicked(object sender, EventArgs e)
{
    string content = await Getusers(); //Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation
    List<Users> _users = JsonConvert.DeserializeObject<List<Users>>(content); //Deserializes or converts JSON String into a collection of Post
    var userName = txtUserName.Text;
    var password = txtPassword.Text;
    var isValidUser = _users.Where(w => w.UserName == userName && w.password == password).FirstOrDefault();
    var driverId = _users.Where(w => w.UserName == userName && w.password == password).FirstOrDefault().ID;         


    if (isValidUser != null)
    {

            Application.Current.Properties["driverId"] = driverId;
            Application.Current.MainPage = new MainPage();
    }
    else
    {
            lblError.Text = "Error your credentials are invalid, please try again";
    }         

  }

标签: xamarinxamarin.formsdotnet-httpclient

解决方案


推荐阅读