0

I have a simple function which does a GET request using HTTPClient SendAsync.

I’m in the process of moving to MAUI and I’ve ported this across from our Xamarin app. This function returns correctly when running with Xamarin, but with MAUI it appears that the JSON payload data is not going through to our WordPress API correctly and the API responds with 400s or 403s.

I am testing on an Android emulator (API 33).

The code is as follows;

    // at class initialisation
    var clientHandler = new HttpClientHandler()
    {
        ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
    };

    httpClient = new HttpClient(clientHandler)
    {
        Timeout = TimeSpan.FromMilliseconds(timeOut)
    };
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
    httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");

    // further down the class
    public async Task<string> Get<T>(T item, string path, bool https = false)
    {
        var data = JsonConvert.SerializeObject(item);

        var requestMethod = "http://";

        if (https)
        {
            requestMethod = "https://";
        }

        var serverString = requestMethod + path;

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(serverString),
            Content = new StringContent(data, Encoding.UTF8, "application/json"),
        };

        HttpResponseMessage response = await httpClient.SendAsync(request);
        HttpContent Content = response.Content;
        var json = await Content.ReadAsStringAsync();
        response.Dispose();
        return json;
    }

For example, here is a simple call to the Posts endpoint, requesting a list of blog posts;

https://[website_address]/wp-json/wp/v2/posts

The JSON data is as follows;

{ "context":"view", "id":0, "page":1, "per_page":100, "search":"", "order":"desc", "orderby":"date", "status":"publish", "sticky":false }

On Xamarin the result is (blog post data returned as expected): XAMARIN

On MAUI, the result is (403, API is assuming I am trying to create a blog post?!): MAUI

Additionally, I’ve tested a “normal” Get operation and it works fine (i.e. a HTTPClient.Get). Hopefully someone out there with a larger brain knows why, thanks in advance!

12
  • are u using the same code to call the api in maui Commented May 14, 2023 at 13:58
  • Hi @user123456, yes the entire class is the same. Commented May 14, 2023 at 14:14
  • How does your server authenticate users? A 403 means an auth failure Commented May 14, 2023 at 14:45
  • that what i was wondering in Maui, you need token @Jason Commented May 14, 2023 at 14:49
  • 2
    you need to look in the logs at the actual request received by your service and compare the working and non working requests Commented May 14, 2023 at 16:26

1 Answer 1

0

Thanks to everyone for their input. After trying various approaches with the HTTPClient/HttpRequestMessage combination without any luck, I manage to get it working using the RestSharp library where I was able to execute a GetAsync with the JSON data as part of the parameters of the request.

    public async Task<string> Get<T>(T item, string path, bool https = false)
    {
        var data = JsonConvert.SerializeObject(item);

        var requestMethod = "http://";

        if (https)
        {
            requestMethod = "https://";
        }

        var serverString = requestMethod + path;

        var options = new RestClientOptions
        {
            BaseUrl = new Uri(serverString),
            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
        };
        var client = new RestClient(options);

        var request = new RestRequest
        {
            Method = Method.Get,
            Timeout = Convert.ToInt32(timeOut),
        };
        request.AddHeader("Authorization", "Bearer " + AuthorisationToken);
        request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        request.AddHeader("Accept", "application/json");
        request.AddParameter("application/json", data, ParameterType.GetOrPost);

        var response = await client.GetAsync(request);
        return response.Content;
    }

Hopefully this helps anyone out there who comes across this strange issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.