Unity打包APK出现‘Cannot connect to destination host’连接错误求助
问题排查与解决方案
1. 服务器地址错误(核心原因)
你代码中使用的http://localhost:7000/api/chat仅在Unity编辑器环境有效——此时localhost指向你的开发电脑。但打包为APK后,localhost会指向Android设备自身,而你的服务器运行在电脑上,导致设备无法建立连接。
解决方式:
- 将
localhost替换为开发电脑在局域网内的实际IP地址(例如http://192.168.1.100:7000/api/chat),确保Android设备与电脑处于同一Wi-Fi网络。 - 若需外网访问,需将服务器部署至公网,或使用内网穿透工具映射端口后改用对应公网地址。
2. Android明文HTTP限制
Android 9(API级别28)及以上系统默认禁止应用发起明文HTTP请求,仅允许HTTPS。若你的服务器使用HTTP,APK的请求会被系统拦截。
解决方式:
在Unity项目的Assets/Plugins/Android目录下创建(或修改)AndroidManifest.xml,添加允许明文HTTP的配置:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:icon="@mipmap/app_icon" android:label="@string/app_name" android:supportsRtl="true" tools:ignore="GoogleAppIndexingWarning" android:usesCleartextTraffic="true"> <!-- 允许明文HTTP --> <uses-library android:name="org.apache.http.legacy" android:required="false"/> </application> <!-- 声明网络权限 --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> </manifest>
也可在Unity的Player Settings > Android > Publishing Settings中勾选Custom Main Manifest,再修改生成的Manifest文件。
3. 网络权限缺失
尽管Unity默认会添加网络权限,但打包过程中可能意外丢失。需确认AndroidManifest.xml中包含<uses-permission android:name="android.permission.INTERNET"/>,确保应用具备网络访问权限。
4. 服务器端口/防火墙限制
检查开发电脑的防火墙是否开放了7000端口,确保Android设备能通过局域网访问该端口。可通过Android设备的adb shell执行telnet 你的电脑IP 7000测试连接是否正常。
5. 优化错误日志排查
修改代码中的错误日志输出,增加响应状态码信息,便于精准定位问题:
case UnityWebRequest.Result.ProtocolError: MenuManager.instance.SetLog($"HTTP Error: {webRequest.error}, Response Code: {webRequest.responseCode}"); break;
内容的提问来源于stack exchange,提问作者BlackDragon94
相关产品推荐
相关产品推荐

