0

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);
BrigaDella
  • 131
  • 9
  • If you are targeting Android 8+, then I "assume" the error is related to you using a non-secure (`http`) connection, here is my answer for Xamarin on using `cleartextTrafficPermitted` (of course in production env. you should be using secure connections: https://stackoverflow.com/a/55997456/4984832 – SushiHangover May 02 '20 at 10:17
  • Thanks I'll check it and try it. – BrigaDella May 02 '20 at 10:33
  • You might have to add this header to your client: ("Connection", "close"); if it’s still not working. Also please share your application output (stack trace). And are you having the same issue with iOS as well? – Saamer May 04 '20 at 02:25

1 Answers1

0

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;
}
BrigaDella
  • 131
  • 9