I use Xamarin.Forms and I run my application on the Android-simulator and on my mobile device
When I try to send HttpRequestMessage, my application is turned off. This happens in the SendRequest method, but sometimes I get An error occurred while sending the request
- I use localhost endpoint: http://localhost:62690
- Uri : http://localhost:62690/api/account/login
I also created a console application, tested the request there and everything works, but Android does not.
public async Task<TResult> PostAsync<TResult>(string uri, IRequestData data, string token = "", string header = "")
{
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.AddAuthoriationHeader(token);
var content = data.ToJson();
request.SetContent(content, ContentTypes.Json);
var response = await SendRequestAsync(request);
var result = await HandleResponseAsync<TResult>(response);
return result;
}
public static void SetContent(this HttpRequestMessage request,
string content,
ContentTypes contentType)
{
request.Content = new StringContent(content,
Encoding.UTF8,
contentType.Value());
}
public static string Value(this ContentTypes contentType)
{
switch (contentType)
{
case ContentTypes.XxxForm:
return "application/x-www-form-urlencoded";
case ContentTypes.Json:
return "application/json";
default:
throw new ArgumentOutOfRangeException(nameof(contentType), contentType, null);
}
}
private async Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request)
{
try
{
using (var client = new HttpClient())
{
return await client.SendAsync(request); // Shut down on this line
}
}
catch (ArgumentNullException e)
{
Console.WriteLine(e.Message);
throw;
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
throw;
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
throw;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
What is it can be and why the conversion in the console to the local host is working, but with the phone and emulator error?
10.0.2.2Review : developer.android.com/studio/run/emulator-networking