Tokens94
Tokens94

Reputation: 141

.net Maui - basic web request


Ive been playing with .net Maui and had some success doing Bluetooth LE but for reasons I've gone ahead and changed my implementation to use wifi and a restful API. I am building for both android and IoS. I am testing with a real device, running android 12.

I am trying to make a basic http(s) (tried both http and https) request to a local server (an esp32). My url is:

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

My manifest file:

<?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>

My initialisation function, which gets called when my page is loaded - MainPage()

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

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

and finally, my send function which gets called by a button pressed event

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

I also have a runtime permissions section which asks for location_fine_access, which I've given access for.
When running through the request function, I get an exception thrown with the message:

[DOTNET] Operation is not supported on this platform.

I thought this was a permissions issue, and so android isn't letting me make the request but now I'm not so sure. Anyone else had and resolved this issue?

Upvotes: 1

Views: 4199

Answers (1)

Tokens94
Tokens94

Reputation: 141

Looks as though .net maui doesnt hook into the android http client properly and is an issue on github. https://github.com/dotnet/maui/issues/1260 the suggested work around, which I have tested and works for me, is to instantiate your HttpClient with the native android handler like this as a workaround:

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

Upvotes: 0

Related Questions