Search code examples
c#androidxamarinnetwork-programminghttpclient

Am trying to send data to an external PHP script from xamarin android c#


This is my code below login.cs

var user = User.Text;
var pass = Pass.Text;
 try
    {

        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("username", user));
        postData.Add(new KeyValuePair<string, string>("password", pass));

        var content = new FormUrlEncodedContent(postData);

        HttpClient client = new HttpClient();

        client.BaseAddress = new Uri("Http://10.0.2.2:3307");

        var response = await client.PostAsync("Http://10.0.2.2:3307/login.php", content);
        result = response.Content.ReadAsStringAsync().Result;

    }
    catch (Exception ex)
    {
        await DisplayAlert("Error", ex.ToString(), "Ok");
        return;
    }

But I get a error at this line below saying Java.net.protocol: Unexpected status line "Y. "

    var response = await 
    client.PostAsync("Http://10.0.2.2:3307/login.php", content);

Solution

  • I managed to fix the problem :

    The problem was that i tried to connect to a wrong port and i changed it from 3307 to 80, and also the android emulator uses the same ip address as xampp so i had to check the documentation on how to connect to an external local server. You can check here:

    https://developer.android.com/studio/run/emulator-networking

    And i used json to parse the user model class instead of using KeyValuePair because it didn't work as well.

    var user = User.Text;
    var pass = Pass.Text;
    try{
    
        User us = new User();
        us.username = user;
        us.password = pass;
    
        string json = JsonConvert.SerializeObject(us);
    
        var content = new StringContent(json, Encoding.UTF8, "application/json");
    
        HttpClient client = new HttpClient();
    
        Uri uri = new Uri("Http://10.0.2.2:80/api/login.php");       
    
        client.BaseAddress = new Uri("Http://10.0.2.2:80");
    
        HttpResponseMessage response = await client.PostAsync(uri, cont);
        string  result =  await response.Content.ReadAsStringAsync();
        result = result.Trim('[', ']');
    
        dynamic output = JsonConvert.DeserializeObject(result);
    
    }
    catch (Exception ex)
    {
        await DisplayAlert("Error", ex.ToString(), "Ok");
        return;
    }