如何从Android模拟器访问localhost? [英] How to access localhost from android emulator?

查看:621
本文介绍了如何从Android模拟器访问localhost?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在本教程中学习Xamarin-将用户注册为Xamarin Forms中的ASP.NET身份.如果邮递员发送请求,一切都正常.但是,如果我想使用android仿真器,它将无法正常工作.而且我无法使用UWP,因为必须启用开发人员模式并且我的公司计算机上没有管理员权限.我在我的私人计算机上启用了开发人员模式,它可以在UWP上运行,但不能在android模拟器上运行.在教程中使用的是UWP,那个家伙说对于android模拟器需要一些配置,但是他没有透露任何细节.

I am studying Xamarin from this tutorial - Signup user to ASP.NET Identity from Xamarin Forms. Everything is working if a send request with postman. But if I want to use android emulator it is not working. And I cannot use UWP, because developer mode has to be enabled and I don’t have admin rights on my company computer. I enabled developer mode on my private computer and it is working on UWP but it is not working on android emulator. In the tutorial is used UWP and the guy said that for the android emulator is needed some configuration, but he did not tell any details.

我读了许多文章,似乎问题出在我的后端(在localhost上运行)和android模拟器之间的连接中. android模拟器是否是尝试调用我的本地主机的单独机器是否正确?我尝试将localhost更改为127.0.0.1或10.0.2.2,并尝试了此所有选项文章.但这不起作用.

I read many articles and it seems that problem is in the connection between my backend (running on localhost) and android emulator. Is it correct that android emulator is a separate machine trying to call my localhost? I tried to change localhost to 127.0.0.1 or 10.0.2.2 and I tried all options from this article. But it is not working.

我对,必须更改本地主机吗?如果是这样,在哪里?还是其他地方有问题?

Am I right that localhost has to be changed? If so, where? Or is problem somewhere else?

Api服务注册方法:

Api services Register method:

    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;
        }
   }

如果我使用本地主机,则为异常:

Exception if I use 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,则请求错误:

Bad request if I use 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 }}

推荐答案

localhost是指您的本地计算机.人们普遍认为Android模拟器(或iOS)也是localhost的一部分,这是一个常见错误,因为它在同一台计算机上运行.但这不是事实.

localhost refers to your local machine. It's a common mistake that people think that the Android emulator (or iOS for that matter) is also part of localhost since it is running on the same machine. But this isn't the case.

仿真器在您的设备中作为设备运行,并像模拟物理设备一样模拟工作.它具有自己的IP地址,无法到达您的localhost回送地址.您的应用程序在另一台计算机(即te仿真器)上作为应用程序运行.使用UWP时会造成一些混乱,因为确实是作为本地计算机上的应用程序运行的.

The emulators are running as a device in your device and mimic the working as if it was a physical device. It has it's own IP address and cannot reach your localhost loopback address. Your app runs as a application on another machine, namely te emulator. It gets a bit confusing when using UWP, since this does run as an application on your local machine.

这就是为什么您必须使用托管服务器应用程序的计算机的网络地址的原因.该地址通常以192.168.x.x10.x.x.x开头,并且可以在计算机的网络设置中找到.

That is why you would have to use the network address of your machine where the server application is hosted. This address typically starts with 192.168.x.x or 10.x.x.x and can be found in the network settings of your machine.

似乎您已经发现了这一点.使用10.0.2.2地址时,您会收到HTTP400.这意味着请求中的内容不正确,但是您可以由此得出结论,实际上可以访问服务器应用程序.但是请求的内容在您的服务器应用程序中引起了问题.由于您没有为/Account/Register端点提供任何代码,因此无法确定发生了什么.在服务器代码中放置一个断点,重试该请求,然后尝试查看为什么触发了HTTP 400.

It seems that you already discovered this. When using the 10.0.2.2 address you receive a HTTP 400. Which means something in your request wasn't right, but you can conclude from this that the server application can actually be reached. But the content of the request causes a problem in your server app. Since you do not provide any code for the /Account/Register endpoint it is impossible to tell what is going on there. Put a breakpoint in your server code, retry the request and try to see why a HTTP 400 is triggered.

这篇关于如何从Android模拟器访问localhost?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆