10

我只是在 android 模拟器上制作一个基本的 Webview 应用程序,无法连接到我计算机上托管的网站。

这是我的代码:

安卓清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.emswebviewer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>

主要活动 Java 文件:

public class MainActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        System.out.println("*** My thread is now configured to allow connection");
    }
    setContentView(R.layout.activity_main);

    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("http://10.0.2.2:8080");
}

终端(在本地主机端口 8080 上启动网站):

Michaels-MacBook-Pro-5:web michael$ php -S localhost:8080
PHP 5.5.14 Development Server started at Mon Dec 22 14:08:01 2014
Listening on http://localhost:8080

httpd.conf 文件(在 Apache 文件夹下):

#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/Applications/MAMP/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options All

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride All

#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all

我使用 Mamp 和 AVD 作为模拟器。

当我运行我的应用程序时,它会在主活动页面上返回 net::ERR_CONNECTION_REFUSED。

我需要在某处允许外部连接吗?或者我正在尝试做的事情有什么本质上的错误吗?

4

4 回答 4

8

模拟器上的 localhost 它不是桌面上的 localhost。在您的桌面上,您需要使用 php -S 10.0.2.2:8080 运行 php 服务器(如果这是您的 IP)。而不是在您的应用程序中使用 WebView 从模拟器访问该 IP。您无法从模拟器访问桌面的本地主机(至少不能直接访问)。不要仅在本地主机上启动您的服务器。

于 2018-05-21T14:13:29.250 回答
0

查找此文件 ports.conf 并在必要时添加 Listen 8080 并重新启动服务器。

于 2018-05-21T10:48:23.740 回答
0

对我有用的是用我的笔记本电脑 192.168.2.7 替换本地主机地址,就我而言。@gorlok 评论帮助我找到了解决方案。

于 2020-03-25T09:35:46.743 回答
0

无论如何,使用10.0.2.2是正确的并且没有错。您可以在下面的答案中看到原因

为什么我们使用 10.0.2.2 连接到本地 Web 服务器而不是在 android 客户端中使用计算机 IP 地址

该问题可能与您的应用程序127.0.0.1仅侦听而不是所有接口有关。你需要确保你使用类似下面的东西

php -S 0.0.0.0:8080

我也看到了你的赏金问题,它也回答了你需要运行你的 Django 服务器,如下所示

python manage.py runserver 0.0.0.0:8000

PS:下次你发布赏金@kingraphaII时,请善待人们,不要只是做鬼

于 2018-05-22T05:42:54.597 回答