Hickori
Hickori

Reputation: 105

Error in HttpClient .NET MAUI when doing a POST with a body

I have a problem with my .NET Maui app, so I have a HttpService class where I can easily fetch the response of a Post/Get request. But when run my app on my local Android device and do a "Post" and have a body I get this error:

    {System.ObjectDisposedException: Cannot access a closed Stream.
   at System.IO.MemoryStream.EnsureNotClosed()
   at System.IO.MemoryStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
   at Xamarin.Android.Net.AndroidMessageHandler.WriteRequestContentToOutput(HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 458
   at Xamarin.Android.Net.AndroidMessageHandler.DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 533
   at Xamarin.Android.Net.AndroidMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 375
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at MyApp.Services.HttpService.PostAsync(String url, String body, String token, Dictionary`2 headers) in C:\Users\user\Documents\temp\MyApp\MyApp\Services\HttpService.cs:line 38}

Here is my method:

public async Task<string> PostAsync(string url, string body = "", string? token = "", Dictionary<string, string> headers = null)
    {
        HttpClient client = new();
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = new StringContent("", Encoding.UTF8, "application/json"),
            };

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            if (token != "") request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);


            var result = await client.PostAsync(url, new StringContent("", Encoding.UTF8, "application/json"));
            //var result = await client.SendAsync(request);

            var test = await result.Content.ReadAsStringAsync();

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Något gick fel");
            }

            return await result.Content.ReadAsStringAsync();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

I have tried both "SendAsync" and "PostAsync" but none of them work. But SendAsync works if I send the HttpRequestMessage and comment out the "Content = ..." part.

It works flawless if I debug it on my windows machine. I dont have any more android devices to test it on unfortunatley.. I will try the emulator and write the result.

**Same result on the emulator.

Upvotes: 1

Views: 2061

Answers (2)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13919

Please change the prefix of URL from

http://

to

https://

Upvotes: 1

Kathir M
Kathir M

Reputation: 31

See the below Sample code for dotnet maui Post request using httpclient

     var client = new HttpClient();
 var content = new StringContent($"{{\"image\":\"{image}\"}}", Encoding.UTF8, "application/json");
 var response = await client.PostAsync("https://url", content);

 if (response.IsSuccessStatusCode)
 {
     return response.ReasonPhrase;
     // Handle success
 }
 else
 {
     return "Failed";
 }

Upvotes: 0

Related Questions