Search code examples
androidhttpxamarinrequestresponse

Android HTTP request and response


I want to send a http post request from a controller when I login on Xamarin.Android. This is my C# code from the Login_Activity

btn_login_001.Click += (sender, e) =>{
    User user = new User(edit_user_001.Text.ToString(), edit_password_001.Text.ToString());
    User_controller user_controller = new User_controller();
    Task<HttpResponseMessage> response = user_controller.check_pass_void(user);

    switch (response.Status){
       case 200:
           Console.WriteLine("Status OK");
           break;
       case 404:
           Console.WriteLine("Status Not Found");
           break;
       default:
           Console.WriteLine("Status Other");
           break;
   }
};

Also, this is my code from the controller

class User_controller {

  HttpClient client = new HttpClient();

  public async Task<HttpResponseMessage> check_pass_void(User user){

    try {
        Uri uri = new Uri("http://192.168.1.130:8080/noguiana/usuario/check_pass_void");

        // Convertir el usuario a JSON
        string user_json = JsonConvert.SerializeObject(user);
        StringContent content = new StringContent(user_json, Encoding.UTF8, "application/json");

        return await client.PostAsync(uri, content);

    } catch {
        return null;
    }

  } 
}

My error is that Task<HttpResponseMessage> is not a simple HttpResponseMessage. Xamarin foces me to return Task<HttpResponseMessage> and now I'm on trouble using http methods like status or desseliarizing my JSON responses.

If I cast, Task<HttpResponseMessage> response = user_controller.check_pass_void(user); to HttpResponseMessage response = (HttpResponseMessage)user_controller.check_pass_void(user); it give me this massage:

enter image description here

What can I do?


Solution

  • you need to learn to use async/await properly

    // mark the event handler as async
    btn_login_001.Click += async (sender, e) =>{
    
       ...
    
       // check_pass_void() is async, so you need to await it
       HttpResponseMessage response = await user_controller.check_pass_void(user);
    
       ...