Search code examples
xamarin.formsjson.nethttp-postvisual-studio-2019

Why doesn't my PHP website receive the variable that I send POST from an Android Xamarin app?


I can't see the result that I send from a Visual Basic 2019 Xamarin Forms app to a PHP REST. Basically this is what I do in the Mainpage.xaml.cs:

protected override async void OnAppearing()
        {
            HttpClient client = new HttpClient();
            Uri uri = new Uri("https://www.miweb.com/prueba.php");
            Msj mensaje = new Msj { Mensaje = "PRUEBAAAAAA" };
            string json = JsonConvert.SerializeObject(mensaje);
            var content = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
            //HttpResponseMessage response = client.PostAsync(uri, content).Result;
            using (var response = await client.PostAsync(uri, content))
            {
            }

            base.OnAppearing();
        }

The class Msj:

    internal class Msj
    {
        public string Mensaje { get; internal set; }
    }

And this is the PHP code:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $input = $_POST;
    header("HTTP/1.1 200 OK");
    $file = fopen("app.txt", "w");
    fwrite($file, json_encode($input['Mensaje']) . PHP_EOL);
    fclose($file);
    exit();
}

The app.txt file is created, but its content is "null" (without quotes.)


Solution

  • Finally I solved so, without JSON. Thanks to all:

    protected override async void OnAppearing()
    {
        HttpClient client = new HttpClient();
        Uri uri = new Uri("https://www.miweb.com/prueba.php");
        var datos = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("mensaje", "SOLVED!")
        };
        var content = new FormUrlEncodedContent(datos);
        using (var response = await client.PostAsync(uri, content))
        {
        }
        base.OnAppearing();
    }