1

I am writing a mobile application in Xamarin.Forms, and have a very simple PHP file for my back end. The mobile application sends a post request to the PHP file, and the PHP file is meant to var_dump the post contents.

<?php     
     echo "Your post response is...";
     var_dump($_POST);
?>

My Xamarin application uses the HttpClient class to create a simple post request using the PostAsync() method.

public class RestService
    {
        HttpClient client;
        private const string URL = "https://braz.io/mobile.php";

        public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
        }

        public async Task<string> getUserInformation()
        {
            User u = new User("Barns", "password1234", "email@email.com");
            string json = JsonConvert.SerializeObject(u);
            var uri = new Uri(string.Format(URL, string.Empty));
            try
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                StringContent s = new StringContent(json);
                var response = await client.PostAsync(uri, s);
                string body = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {Console.WriteLine(ex);}

            return null;
        }
    }

For some reason, my post request is only getting the response Your post resonse is... followed by an empty array. It is strange, because when I use PostMan on google chrome, it returns the correct information.

I have checked that my json variable has valid JSON in it as well, so I am unsure why the PostAsync function is returning/sending an empty array from/to my PHP file.

UPDATE as per comment request

The JSON I am sending is as follows:

"{\"username\":\"Barney\",\"password\":\"1234\",\"email\":\"email@email.com\"}"

My user class is:

public class User
{
    public User(){ }

    public string username { get; set; }
    public string password { get; set; }
    public string email { get; set; }

    public User(string username, string password, string email)
    {

        this.username = username;
        this.password = password;
        this.email = email;
    }
}
Ronak Vachhani
  • 214
  • 2
  • 14
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

1 Answers1

2

The issue has nothing to do with the Xamarin side of things. Your issue lies in the PHP code you provided and the fact that when you tried sending something with POSTman, you didn't send it as the body of the request.

In order to read the request body, you need to read the input stream:

$json = file_get_contents('php://input');

Then you can output that with

var_dump($json);

As for your RestService code, I would advise you to provide the content type for your string content:

var s = new StringContent(json, Encoding.UTF8, "application/json");
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118