简体   繁体   English

如何在 Xamarin Forms 中创建一个 Httpclient 实例

[英]How to create one instance of Httpclient in Xamarin Forms

是否可以在OnStart() Xamarin Forms 应用程序中创建一个httpclient实例并在我的应用程序中的任何地方使用它?

Yes you can use the same httpclient for all request in your app.是的,您可以对应用程序中的所有请求使用相同的 httpclient。 But you will need to take note that if there is API that is having different base URL or headers information, then you will need to create another httpclient for that.但是您需要注意,如果 API 具有不同的基本 URL 或标头信息,那么您需要为此创建另一个 httpclient。

What I do is I have a class to manage the HttpClient instances.我所做的是我有一个类来管理 HttpClient 实例。 If there is no instance that is matching the HttpConfig, it will create and store it.如果没有与 HttpConfig 匹配的实例,它将创建并存储它。 If there is already an existing instance, it will just return it.如果已经有一个现有的实例,它只会返回它。

Example of code (HttpService is dependency injected):代码示例(HttpService 是依赖注入):

public class HttpService : IHttpService
{
    private static readonly int MAX_CLIENT = 5;

    private Dictionary<HttpConfig, HttpClient> mClients;
    private Queue<HttpConfig> mClientSequence;

    public HttpService()
    {
        mClients = new Dictionary<HttpConfig, HttpClient>();
        mClientSequence = new Queue<HttpConfig>();
    }

    private HttpClient CreateHttpClientAsync(HttpConfig config)
    {
        HttpClient httpClient;

        if (mClients.ContainsKey(config))
        {
            httpClient = mClients[config];
        }
        else
        {
            // TODO: Create HttpClient...

            if (mClientSequence.Count >= MAX_CLIENT)
            {
                // Remove the first item
                var removingConfig = mClientSequence.Dequeue();
                mClients.Remove(removingConfig);
            }

            mClients[config] = httpClient;
            mClientSequence.Enqueue(config);
        }

        return httpClient;
    }
...
}

HttpConfig is class where I store BaseUrl, Timeout, Headers, Auth info, etc. You will need to override the Equals method in the class for comparison whether there is existing same config. HttpConfig 是我存储 BaseUrl、Timeout、Headers、Auth 信息等的类。您需要覆盖类中的 Equals 方法以比较是否存在相同的配置。

public override bool Equals(object obj)
{
    // Logic to determine whether it is same config
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM