我阅读了很多文章,看起来问题在于我的后端(在本地主机上运行)和Android模拟器之间的连接。 Android模拟器是一个独立的机器,试图调用我的本地主机,这是正确的吗?我尝试将localhost更改为127.0.0.1或10.0.2.2,并尝试了此文章中的所有选项,但都不起作用。
我是否正确认为localhost必须更改?如果是这样,应该在哪里更改?还是问题出在其他地方?
Api服务注册方法:
public async Task<bool> RegisterAsync(string email, string password, string confirmPassword)
{
try
{
System.Diagnostics.Debug.WriteLine("Email: " + email);
var client = new HttpClient();
var model = new RegisterBindingModel
{
Email = email,
Password = password,
ConfirmPassword = confirmPassword
};
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("http://localhost:49205/api/Account/Register", content);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: " + e);
throw;
}
}
使用localhost时出现异常:
{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000b6] in <bcdc1df2b3724ab69797f3819a126346>:0
at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0016d] in <bcdc1df2b3724ab69797f3819a126346>:0 --- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream (System.IAsyncResult asyncResult) [0x0003a] in <bcdc1df2b3724ab69797f3819a126346>:0
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <fcbf47a04b2e4d90beafbae627e1fca4>:0
如果我使用10.0.2.2,会出现错误请求:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent,
Headers: {Server: Microsoft-HTTPAPI/2.0 Date: Thu, 17 May 2018 09:08:41 GMT Connection: close Content-Type: text/html; charset=us-ascii Content-Length: 334 }}