簡體   English   中英

.net Maui - 基本網絡請求

[英].net Maui - basic web request


我一直在使用 .net Maui 並在藍牙 LE 方面取得了一些成功,但由於某些原因,我繼續前進並改變了我的實現以使用 wifi 和一個 restful API。 我正在為 android 和 IoS 構建。 我正在使用運行 android 12 的真實設備進行測試。

我正在嘗試向本地服務器(esp32)發出基本的http(s)(嘗試了http和https)請求。 我的網址是:

const string url = "https://192.168.4.1/api";

我的清單文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="31" />
    <application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true"></application>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

我的初始化函數,在我的頁面加載時調用 - MainPage()

private void init_network()
{
    client = new HttpClient();

    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}

最后,我的發送函數被按鈕按下事件調用

private bool SendCommand(string command)
{ 
    try
    {
        var msg = new HttpRequestMessage(HttpMethod.Post, url);
        msg.Content = JsonContent.Create(command);
        HttpResponseMessage response = client.Send(msg); // line where the code throws exception

        if (response.IsSuccessStatusCode)
        {
            return true;
        }
    }
    catch (Exception err)
    {
        Console.WriteLine(err.Message);
    }
    return false;
}

我還有一個運行時權限部分,它要求我授予訪問權限的 location_fine_access。
通過請求函數運行時,我收到一條異常消息:

[DOTNET] Operation is not supported on this platform.

我認為這是一個權限問題,所以 android 不允許我提出請求,但現在我不太確定。 其他人有並解決了這個問題嗎?

看起來 .net maui 沒有正確連接到 android http 客戶端,並且是 github 上的一個問題。 https://github.com/dotnet/maui/issues/1260建議的解決方法(我已經測試過並為我工作)是使用本機 android 處理程序實例化您的 HttpClient 作為一種解決方法:

new HttpClient(new Xamarin.Android.Net.AndroidMessageHandler()).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM