xamarin 在.NET MAUI应用程序中创建和使用HttpClient

3okqufwl  于 2022-12-07  发布在  .NET
关注(0)|答案(2)|浏览(335)

我们在.NET MAUI应用程序中创建/使用HttpClient的方式与在Web或API应用程序中创建,使用x1m0 n1,的方式相同吗?具体来说,我使用IHttpFactory将我的HttpClient添加到Program.cs中的应用程序中--见下文:

builder.Services.AddHttpClient("NamedClient1", config =>
{
    var url = currentState == "production"
        ? "https://my-production-url"
        : "https://sandbox-url";
    config.BaseAddress = new Uri(url);
});

我理解.NET MAUI的想法是标准化我们处理事情的方式。当我尝试在我的.NET MAUI应用程序中添加builder.Services行时,IntelliSense并不建议使用AddHttpClient

chy5wohz

chy5wohz1#

Temperature.xaml.cs

using System.Diagnostics.Metrics;
using System.Text.Json;
using System.Xml.Serialization;

namespace TPMaui3.Views;

public partial class vTemperature : ContentPage
{
    public vTemperature()
    {
        InitializeComponent();
    }

    private void AfficheTemperature(object sender, EventArgs e)
    {
        LireTemperature();
    }

    private async void LireTemperature()
    {
        Uri uri = new("http://meteorestsrvmobile.lab3il.fr/RestServiceMeteo.svc/xml/1");

        try
        {
            HttpClient client = new();
            HttpResponseMessage response = await client.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {
                String content = await response.Content.ReadAsStringAsync();
                content = content.Substring(content.IndexOf("<XMLDataResult>") + 15);
                content = content.Substring(0, content.IndexOf("</XMLDataResult>"));
                lbTemp.Text = content + " °C";
            }
        }
        catch (Exception ex)
        {
            await this.DisplayAlert("Error", ex.Message, "OK");
        }
    }
}

vMeteo.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="TPMaui3.Views.vMeteo"
    Title="Météo"
>
    <VerticalStackLayout Spacing="20" Margin="10" >
        <Label
            Text="Météo"
            x:Name="lbMeteo"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Primary}"
        />
        <Label
            Text="?"
            x:Name="lbTemperature"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbPression"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbHumidite"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbPrecipitationJour"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbTemperatureRessentie"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbVentDirection"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
        <Label
            Text="?"
            x:Name="lbVentVitesse"
            VerticalOptions="Center"
            HorizontalOptions="Center" 
            FontSize="Medium" 
            TextColor="{StaticResource Secondary}"
        />
    </VerticalStackLayout>
</ContentPage>

vMeteo.xaml.cs

using System.Diagnostics.Metrics;
using System.Text.Json;
using TPMaui3.Models;

namespace TPMaui3.Views;

public partial class vMeteo : ContentPage
{
    public vMeteo()
    {
        InitializeComponent();
        Meteo();
    }

    private async void Meteo()
    {
        Uri uri = new("http://meteorestsrvmobile.lab3il.fr/RestServiceMeteo.svc/jsontmps");
        try
        {
            HttpClient client = new();
            HttpResponseMessage response = await client.GetAsync(uri);
            JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions();

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                result = result.Replace("{\"JSONDataTmpsResult\":", "");
                result = result.Replace("}}", "}");

                var vMeteo = Newtonsoft.Json.JsonConvert.DeserializeObject<CMeteo>(result);
                lbMeteo.Text = "Relevé à " + vMeteo.DateReleve.ToString();
                lbTemperature.Text = "Temp: " + vMeteo.Temperature.ToString() + " °C";
                lbHumidite.Text = "Hum: " + vMeteo.Humidite.ToString() + " %";
                lbPression.Text = "Pres: " + vMeteo.Pression.ToString() + " hPa";
                lbTemperatureRessentie.Text = "TR: " + vMeteo.TemperatureRessentie.ToString() + " °C";
                lbPrecipitationJour.Text = "PrecJ: " + vMeteo.PrecipitationJour.ToString() + " mm";
                lbVentVitesse.Text = "Vit: " + vMeteo.VentVitesse.ToString() + " m/s";
                lbVentDirection.Text = "Vent: " + vMeteo.VentDirection.ToString();
            }
        }
        catch (Exception ex)
        {
            await this.DisplayAlert("Error", ex.Message, "OK");
        }
    }
}

CMeteo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TPMaui3.Views;

namespace TPMaui3.Models;

internal class CMeteo
{
    public CMeteo()
    {
    }

    public string DateReleve { get; set; }
    public string Temperature { get; set; }
    public string Pression { get; set; }
    public string Humidite { get; set; }
    public string PrecipitationJour { get; set; }
    public string TemperatureRessentie { get; set; }
    public string VentDirection { get; set; }
    public string VentVitesse { get; set; }
}
iszxjhcz

iszxjhcz2#

移动的开发中的HttpClient与Web有点不同。设备本身处理HttpClient很好,我们不必太担心使用nuget包(Microsoft.Extensions.Http)正确地处理它。所以你可以很好地使用AddSingleton,或者甚至使用HttpClient的静态只读。.NET MAUI团队确保HttpClient类是这样配置的。
来源于微软:
NET MAUI模板将HttpClient类Map到利用每个平台的本机网络堆栈的代码。

相关问题