从 iOS 模拟器和 Android 模拟器连接到本地 Web 服务Connect to local web services from iOS simulators and Android emulators

02/04/2021

本文内容

许多移动应用程序使用 Web 服务。Many mobile applications consume web services. 在开发阶段,在本地部署 Web 服务和从 iOS 模拟器或 Android 模拟器中运行的移动应用程序中使用它是很常见的操作。During the development phase, it's common to deploy a web service locally and consume it from a mobile application running in the iOS simulator or Android emulator. 这可避免向托管的终结点部署 Web 服务并可直接进行调试体验,因为移动应用程序和 Web 服务都是在本地运行的。This avoids having to deploy the web service to a hosted endpoint, and enables a straightforward debugging experience because both the mobile application and web service are running locally.

在 iOS 模拟器或 Android 模拟器中运行的移动应用程序可以使用在本地运行并通过 HTTP 公开的 ASP.NET Core Web 服务,如下所示:Mobile applications running in the iOS simulator or Android emulator can consume ASP.NET Core web services that are running locally, and exposed over HTTP, as follows:

在 iOS 模拟器中运行的应用程序可以通过你的计算机 IP 地址或通过 localhost 主机名连接到本地 HTTP Web 服务。Applications running in the iOS simulator can connect to local HTTP web services via your machines IP address, or via the localhost hostname. 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地 HTTP Web 服务,在 iOS 模拟器中运行的应用程序可以通过向 http://localhost:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local HTTP web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running in the iOS simulator can consume the operation by sending a GET request to http://localhost:/api/todoitems/.

在 Android 模拟器中运行的应用程序可以通过 10.0.2.2 地址连接到本地 HTTP Web 服务,该地址是你的主机环回接口的别名(在开发计算机上为 127.0.0.1)。Applications running in the Android emulator can connect to local HTTP web services via the 10.0.2.2 address, which is an alias to your host loopback interface (127.0.0.1 on your development machine). 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地 HTTP Web 服务,在 Android 模拟器中运行的应用程序可以通过向 http://10.0.2.2:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local HTTP web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running in the Android emulator can consume the operation by sending a GET request to http://10.0.2.2:/api/todoitems/.

但是,若要使在 iOS 模拟器或 Android 模拟器上运行的应用程序能够使用通过 HTTP 公开的本地 Web 服务,还需要执行额外的步骤。However, additional work is necessary for an application running in the iOS simulator or Android emulator to consume a local web service that is exposed over HTTPS. 对于此方案,流程如下:For this scenario, the process is as follows:

在你的计算机上创建一个自签名的开发证书。Create a self-signed development certificate on your machine. 有关详细信息,请参阅创建开发证书。

配置项目,以便将合适的 HttpClient 网络堆栈用于调试版本。Configure your project to use the appropriate HttpClient network stack for your debug build. 有关详细信息,请参阅配置项目。For more information, see Configure your project.

指定本地计算机的地址。Specify the address of your local machine. 有关详细信息,请参阅指定本地计算机地址。

绕过本地开发证书安全检查。Bypass the local development certificate security check. 有关详细信息,请参阅绕过证书安全检查。

将依次讨论每项。Each item will be discussed in turn.

创建开发证书Create a development certificate

安装 .NET Core SDK 会将 ASP.NET Core HTTPS 开发证书安装到本地用户证书存储。Installing the .NET Core SDK installs the ASP.NET Core HTTPS development certificate to the local user certificate store. 但是,尽管证书已安装,但它不受信任。However, while the certificate has been installed, it's not trusted. 若要信任该证书,请执行以下一次性步骤,以运行 dotnet dev-certs 工具:To trust the certificate, perform the following one-time step to run the dotnet dev-certs tool:

dotnet dev-certs https --trust

下面的命令提供有关 dev-certs 工具的帮助:The following command provides help on the dev-certs tool:

dotnet dev-certs https --help

或者,当你运行使用 HTTPS 的 ASP.NET Core 2.1 项目(或更高版本)时,Visual Studio 将检测是否缺少开发证书并提供安装和信任。Alternatively, when you run an ASP.NET Core 2.1 project (or above), that uses HTTPS, Visual Studio will detect if the development certificate is missing and will offer to install it and trust it.

备注

ASP.NET Core HTTPS 开发证书是自签名证书。The ASP.NET Core HTTPS development certificate is self-signed.

有关在计算机上启用本地 HTTPS 的详细信息,请参阅启用本地 HTTPS。For more information about enabling local HTTPS on your machine, see Enable local HTTPS.

配置项目Configure your project

在 iOS 和 Android 上运行的 Xamarin 应用程序可以指定 HttpClient 类使用的是哪个网络堆栈,可选择托管网络堆栈或本机网络堆栈。Xamarin applications running on iOS and Android can specify which networking stack is used by the HttpClient class, with the choices being a managed network stack, or native network stacks. 托管堆栈提供与现有 .NET 代码的高级别兼容性,但限于 TLS 1.0 且速度可能更慢并导致更大的可执行文件大小。The managed stack provides a high level of compatibility with existing .NET code, but is limited to TLS 1.0 and can be slower and result in a larger executable size. 本机堆栈运行速度会更快且可以提供更高的安全性,但可能并不会提供 HttpClient 类的全部功能。The native stacks can be faster and provide better security, but may not provide all the functionality of the HttpClient class.

iOSiOS

在 iOS 上运行的 Xamarin 应用程序可以使用托管网络堆栈,或使用本机 CFNetwork 或 NSUrlSession 网络堆栈。Xamarin applications running on iOS can use the managed network stack, or the native CFNetwork or NSUrlSession network stacks. 默认情况下,新 iOS 平台项目使用 NSUrlSession 网络堆栈,以支持 TLS 1.2,并使用本机 API,以便提高性能并减小可执行文件大小。By default, new iOS platform projects use the NSUrlSession network stack, to support TLS 1.2, and use native APIs for better performance and smaller executable size.

AndroidAndroid

在 Android 上运行的 Xamarin 应用程序可以使用托管 HttpClient 网络堆栈,或使用本机 AndroidClientHandler 网络堆栈。Xamarin applications running on Android can use the managed HttpClient network stack, or the native AndroidClientHandler network stack. 默认情况下,新 Android 平台项目使用 AndroidClientHandler 网络堆栈,以支持 TLS 1.2,并使用本机 API,以便提高性能并减小可执行文件大小。By default, new Android platform projects use the AndroidClientHandler network stack, to support TLS 1.2, and use native APIs for better performance and smaller executable size.

指定本地计算机地址Specify the local machine address

iOS 模拟器和 Android 模拟器均提供对本地计算机上运行的安全 Web 服务的访问。The iOS simulator and Android emulator both provide access to secure web services running on your local machine. 但它们的本地计算机地址各不相同。However, the local machine address is different for each.

iOSiOS

iOS 模拟器使用主机网络。The iOS simulator uses the host machine network. 因此,在此模拟器中运行的应用程序可以通过计算机 IP 地址或通过 localhost 主机名连接到在本地计算机中运行的 Web 服务。Therefore, applications running in the simulator can connect to web services running on your local machine via the machines IP address or via the localhost hostname. 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地安全 Web 服务,在 iOS 模拟器中运行的应用程序可以通过向 https://localhost:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local secure web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running on the iOS simulator can consume the operation by sending a GET request to https://localhost:/api/todoitems/.

备注

从 Windows 运行 iOS 模拟器中的移动应用程序时,此应用程序将显示在用于 Windows 的远程 iOS 模拟器中。When running a mobile application in the iOS simulator from Windows, the application is displayed in the remoted iOS simulator for Windows. 但是,此应用程序会在配对的 Mac 上运行。However, the application is running on the paired Mac. 因此,在 Mac 上运行的 iOS应用程序无法对在 Windows 中运行的 Web 服务进行本地主机访问。Therefore, there's no localhost access to a web service running in Windows for an iOS application running on a Mac.

AndroidAndroid

Android模拟器的各个实例独立于开发计算机网络接口,在虚拟路由器的后方运行。Each instance of the Android emulator is isolated from your development machine network interfaces, and runs behind a virtual router. 因此,模拟设备无法看到开发计算机或网络中的其他模拟器实例。Therefore, an emulated device can't see your development machine or other emulator instances on the network.

但是,各个模拟器的虚拟路由器托管着一个包含预分配地址的特殊网络空间,其中 10.0.2.2 地址是主机环回接口的别名(在开发计算机上为 127.0.0.1)。However, the virtual router for each emulator manages a special network space that includes pre-allocated addresses, with the 10.0.2.2 address being an alias to your host loopback interface (127.0.0.1 on your development machine). 因此,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地安全 Web 服务,在 Android 模拟器中运行的应用程序可以通过向 https://10.0.2.2:/api/todoitems/ 发送 GET 请求来使用操作。Therefore, given a local secure web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running on the Android emulator can consume the operation by sending a GET request to https://10.0.2.2:/api/todoitems/.

检测操作系统Detect the operating system

DeviceInfo 类可用于检测应用程序的运行平台。The DeviceInfo class can be used to detect the platform the application is running on. 可将支持访问本地安全 W eb 服务的相应主机名设置如下:The appropriate hostname, that enables access to local secure web services, can then be set as follows:

public static string BaseAddress =

DeviceInfo.Platform == DevicePlatform.Android ? "https://10.0.2.2:5001" : "https://localhost:5001";

public static string TodoItemsUrl = $"{BaseAddress}/api/todoitems/";

有关 DeviceInfo 类的详细信息,请参阅 Xamarin.Essentials:设备信息。For more information about the DeviceInfo class, see Xamarin.Essentials: Device Information.

绕过证书安全检查Bypass the certificate security check

如果试图从在 iOS 模拟器或 Android 模拟器中运行的应用程序调用本地安全 Web 服务,即使在各个平台上使用的是托管网络堆栈,也会引发 HttpRequestException。Attempting to invoke a local secure web service from an application running in the iOS simulator or Android emulator will result in a HttpRequestException being thrown, even when using the managed network stack on each platform. 因为本地 HTTPS 开发证书是自签名证书,而iOS 或 Android 不信任自签名证书。This is because the local HTTPS development certificate is self-signed, and self-signed certificates aren't trusted by iOS or Android. 因此,当应用程序使用本地安全 Web 服务时,需忽略 SSL 错误。Therefore, it's necessary to ignore SSL errors when an application consumes a local secure web service. 在 iOS 和 Android 上使用托管和本机网络堆栈时,这可以通过以下操作实现:将 HttpClientHandler 对象上的 ServerCertificateCustomValidationCallback 属性设置为忽略对本地 HTTPS 开发证书的证书安全检查结果的回调:This can be accomplished when using both the managed and native network stacks on iOS and Android, by setting the ServerCertificateCustomValidationCallback property on a HttpClientHandler object to a callback that ignores the result of the certificate security check for the local HTTPS development certificate:

// This method must be in a class in a platform project, even if

// the HttpClient object is constructed in a shared project.

public HttpClientHandler GetInsecureHandler()

{

HttpClientHandler handler = new HttpClientHandler();

handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>

{

if (cert.Issuer.Equals("CN=localhost"))

return true;

return errors == System.Net.Security.SslPolicyErrors.None;

};

return handler;

}

在此代码示例中,如果待验证的证书不是 localhost 证书,会返回服务器证书验证结果。In this code example, the server certificate validation result is returned when the certificate that underwent validation is not the localhost certificate. 如果是此证书,将忽略验证结果,并返回 true,以指示证书有效。For this certificate, the validation result is ignored and true is returned, indicating that the certificate is valid. 生成的 HttpClientHandler 对象应作为参数传递到调试版本的 HttpClient 构造函数:The resulting HttpClientHandler object should be passed as an argument to the HttpClient constructor for debug builds:

#if DEBUG

HttpClientHandler insecureHandler = GetInsecureHandler();

HttpClient client = new HttpClient(insecureHandler);

#else

HttpClient client = new HttpClient();

#endif

启用 HTTP 明文流量Enable HTTP clear-text traffic

或者,可以将 iOS 和 Android 项目配置为允许明文 HTTP 流量。Optionally, you can configure your iOS and Android projects to allow clear-text HTTP traffic. 如果将后端服务配置为允许 HTTP 流量,则可以在基 URL 中指定 HTTP,然后将项目配置为允许明文流量:If the backend service is configured to allow HTTP traffic you can specify HTTP in the base URLs and then configure your projects to allow clear-text traffic:

public static string BaseAddress =

DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5000" : "http://localhost:5000";

public static string TodoItemsUrl = $"{BaseAddress}/api/todoitems/";

iOS ATS 选择退出iOS ATS opt-out

若要在 iOS 上启用明文本地流量,应通过将以下内容添加到 Info.plist 文件来选择退出 ATS:To enable clear-text local traffic on iOS you should opt-out of ATS by adding the following to your Info.plist file:

NSAppTransportSecurity

NSAllowsLocalNetworking

Android 网络安全配置Android network security configuration

若要在 Android 上启用明文本地流量,应通过在 Resources/xml 文件夹中添加名为 network_security_config.xml 的新 XML 文件来创建网络安全配置。To enable clear-text local traffic on Android you should create a network security configuration by adding a new XML file named network_security_config.xml in the Resources/xml folder. XML 文件应指定以下配置:The XML file should specify the following configuration:

10.0.2.2

然后,在 Android 清单中的”应用程序”节点上配置 networkSecurityConfig 属性:Then, configure the networkSecurityConfig property on the application node in the Android Manifest:

...

相关链接Related links

android模拟器访问本地web应用,从 iOS 模拟器和 Android 模拟器连接到本地 Web 服务...相关推荐

  1. ios怎么玩java模拟器游戏_新方式玩iOS手游 水果模拟器让电脑运行苹果iOS

    新方式玩iOS手游 水果模拟器让电脑运行苹果iOS 作者:阿姆斯特朗雷时间:2020-02-28 分享到: 手机的出现到现在人手一台,从简单的通话短信,到现在方寸间体验到各种新热手游,掌上的这个屏幕给 ...

  2. android pad版本 yy,YY直播 在IOS端、Android端以及WEB端区别。

    作为一名YY直播的深度用户,打算从设计规范.页面布局浅谈YY直播在三个平台的区别. 这是YY直播IOS端的首页,页眉使用滚动式导航(如图一,截的图片看不出来),页眉最右侧添加了一个下拉式菜单(图二), ...

  3. xcode 工程没有模拟器_Xcode只允许我运行iOS设备(没有模拟器)

    Xcode只允许我运行iOS设备(没有模拟器) 我刚刚将一个项目克隆到Xcode中,并试图在模拟器中运行它. 但是,我唯一的选择是iOS设备. 这只是这个项目的独特之处,我不知道如何修复它. 其他人遇 ...

  4. 使用这5款模拟器访问备选操作系统

    模拟器是我平时闲暇时最喜欢琢磨的与科技相关的东西.也许这只是我自己的爱好,但是能够在你的PC上运行一个备用操作系统这件事确实很酷,尤其是当这个备用操作系统很好玩.本文将谈谈这5款旧的和新的模拟器. 1 ...

  5. ios+android+次留,边做iOS边学Android(三):Activity生命周期+通信

    边做iOS边学Android(一):新建一个project 边做iOS边学Android(二):认识几个常用的控件 趁着不忙赶紧多写点,鬼知道后面又有什么需求要忙... 这次就看一下Activity的 ...

  6. ANDROID模拟器访问本地WEB应用10.0.2.2

    在一般的Java Web程序开发中,我们通常使用localhost或者127.0.0.1来访问本机的Web服务,但是如果我们在Android模拟器中也采用同样的地址来访问,Android模拟器将无法正 ...

  7. android模拟器访问本地网站

    电脑设置 1. 安装tomcat,确定本地可以访问127.0.0.1:8080 2. 关闭防火墙 模拟器设置 1.打开浏览器 2. 访问10.0.2.2:8080 127.0.0.1与10.0.2.2 ...

  8. android模拟器访问电脑本机

    做一个website,让android模拟器连上,然后访问数据库,android模拟器如果想访问本地(电脑)的话不能用localhost,也不能用127.0.0.1,这些都会让模拟器访问自身,因为它把 ...

  9. 关于Android模拟器访问本地地址(转)

    Android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,都是访问模拟器自己!这是不行的!  如果想在模拟器sim ...

最新文章

  1. 有勇气的牛排---算法与数据
  2. 加油站(暴力+贪心)
  3. 语言求余和乘除优先级_愉快地学Java语言:第二章基本程序设计 第2讲
  4. 【数字逻辑设计】关于Logisim的使用说明
  5. java从入门到精通_Java大数据:数据库开发从入门到精通
  6. 3.1 语音的产生与感知
  7. Mac系统打开dmg出现 “资源忙” 怎么解决?
  8. 把Android系统签名弄成jks
  9. Python源码剖析-深度探索动态语言核心技术
  10. 关于Oracle的PARALLEL_MAX_SEVERS参数
  11. 伺服电机的工作原理是什么
  12. 悬浮窗一个怎么够?微信新版本满足你的一心多用
  13. python英文单词记忆游戏单词爆破机
  14. 拿什么拯救你的硬盘?十大绝招帮你忙
  15. 中文大写日期转换函数
  16. html文字抖动效果,CSS实现TikTok文字抖动效果示例
  17. 亿道丨三防手机丨手持终端丨零售行业如何选择手持工业终端设备?
  18. 如何招聘软件测试,ÈçºÎÕÐƸµ½µÄÈí¼þ²âÊÔ¹¤³Ìʦ£¿
  19. FUZ-2204-7环形dp
  20. Python异常和异常处理

热门文章

  1. 关于如何训搭建企业自然语自训练库
  2. 成熟锂离子电池管理系统BSM方案,包括pcb,原理图
  3. LASSO坐标下降法Coordinate Descent Method公式推导及代码
  4. 数字集成电路静态时序分析基础(二)
  5. 软件测试方法划分等价类,软件测试基础-软件测试方法之等价类划分.ppt
  6. 微店构造订单页面,自动化抢票
  7. java 来自集合中泛型序列化的bug,难得一遇
  8. python上手度_Python快速上手JSON指南
  9. 19 冲动:像阿尔法狗一样,兼顾直觉和理性
  10. win7c盘空间越来越小_设置电脑桌面文件自动保存到非C盘