【问题标题】:Android doesn't connect to local host or computer IP addressAndroid 无法连接到本地主机或计算机 IP 地址
【发布时间】:2019-04-08 09:31:12
【问题描述】:

我在 Android 中有一个非常基本的注册脚本,但 Android 无法连接到我的本地主机 phpmyadmin 数据库 (XAMPP)。

有人告诉我这可能是我的 XAMPP 设置,或者我使用了错误的 URL,或者我的脚本中需要一个超时块​​。调试了很多方法,但得到的唯一结果是

/创建用户:com.android.volley.NoConnectionError: java.io.EOFException.

现在连那个错误都消失了。我没有收到任何错误,而且我的脚本什么也不做。

这是我的 CreateUser 脚本;

public class CreateUser extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user);
        this.setTitle("Create User");
        final EditText username1 = findViewById(R.id.Createusername);
        final EditText password1 = findViewById(R.id.CreatePassword);
        final Switch isAdmin = findViewById(R.id.isadmin);
        final Button createuser = findViewById(R.id.createuserbtn);
        if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
            isAdmin.setVisibility(View.GONE);
        }
        createuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String username = username1.getText().toString();
                final String password = password1.getText().toString();
                if (isAdmin.getShowText()) {
                    Global.isadmin = "1";
                }else{
                    Global.isadmin ="0";
                }
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if (success){
                                Intent intent = new Intent(CreateUser.this, MainActivity.class);
                                CreateUser.this.startActivity(intent);
                            }else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry",null)
                                        .create()
                                        .show();


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                int socketTimeout = 250000;//30 seconds - change to what you want
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                RegisterRequest registerRequest = new RegisterRequest(username,password,Global.isadmin,responseListener);
                registerRequest.setRetryPolicy(policy);
                RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
                queue.add(registerRequest);
            }
        });
    }

这是我的 RegisterRequest 类;

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:3306/phptesting/Register.php"; //the address was localhost, then my ipaddress, and now its this code i was told to put in
    private Map<String, String> params;
    public RegisterRequest(String username, String password, String isAdmin, Response.Listener<String> listener){
        super(Method.POST, REGISTER_REQUEST_URL,listener,null);
        params = new HashMap<String, String>();
        params.put("username",username);
        params.put("password",password);
        params.put("isAdmin", isAdmin);
    }

    public Map<String, String> getparams() {
        return params;
    }
}

如果您需要,这里是我的 PHP 脚本,位于 XAMPP 的 htdocs 中。

<?php
    $db_host = 'localhost:3306';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'test';

    $con = mysqli_connect($db_host,'user',$db_pass,$db_name);
    if($con){
        echo "connection successful";
    }else{
        echo "connection failed";
    }

    $age = $_POST["isAdmin"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
    if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
    if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
    mysqli_stmt_bind_param($statement, "sss",$username,$password,$isAdmin);
    mysqli_stmt_execute($statement);
    if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }

    $response = array();
    $response["success"] = true;  

    echo json_encode($response);
    ?>

感谢所有帮助,如果有人跟我一起尝试创建这个简单的登录和注册应用程序,我会很高兴。

【问题讨论】:

  • 您的清单是否允许互联网连接?
  • @statosdotcom 是的,
  • 您的 php 文件工作正常吗?并且本地主机地址可以吗?
  • @Lucefer 是的。 Php(在 url 中)有效,但我收到一些警告等。 “连接成功注意事项:未定义索引:第 14 行 C:\xampp\htdocs\testing\Register.php 中的 isAdmin 注意:未定义索引:第 15 行 C:\xampp\htdocs\testing\Register.php 中的用户名 注意:未定义索引:第 16 行 C:\xampp\htdocs\testing\Register.php 中的密码 警告:mysqli_error() 期望参数 1 为 mysqli,对象在第 22 行 C:\xampp\htdocs\testing\Register.php 中给出 { "成功":true}"
  • 那些通知可能会创建一些 html 输出,这不会是 JSON 可解码的 android 端。修复它们。

标签: java php android xampp


【解决方案1】:

由于您在代码中使用了错误的 URL,您遇到了错误。

private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:3306/phptesting/Register.php"; 

我不确定你是否知道。端口号3306 为 MySQL 数据库引擎保留。其中,Apache 服务器使用端口号 80 或任何其他端口(如果您已配置为使用其他端口号)。

现在您需要将该 URL 更改为如下所示(只需删除 :3306)。

private static final String REGISTER_REQUEST_URL = "http://10.0.2.2/phptesting/Register.php"; 

请注意,此 URL (10.0.2.2) 仅适用于 Android 模拟器,不适用于真实设备。因此,我建议您使用在模拟器和真实设备上都可以正常工作的系统(LAN)IP 地址。

如何查看IP地址?

首先将您的系统和手机(或模拟器)连接到同一个 WiFi 网络或移动热点。

然后打开命令提示符,输入ipconfig,它会返回如下输出

C:\Users\user_name>ipconfig

Windows IP Configuration


Wireless LAN adapter Wireless Network Connection 2:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

Wireless LAN adapter Wireless Network Connection:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : ******
IPv4 Address. . . . . . . . . . . : 192.168.1.141
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : ******
                                   192.168.*.*

Ethernet adapter Local Area Connection:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{******}:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

C:\Users\user_name>

现在检查

Wireless LAN adapter Wireless Network Connection:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : ******
IPv4 Address. . . . . . . . . . . : 192.168.1.141
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : ******
                                   192.168.1.1

复制 IPv4 地址 192.168.1.141 并准备一个这样的 URL

private static final String REGISTER_REQUEST_URL = "http://192.168.1.141/phptesting/Register.php";

IP 地址因系统而异。还要记住,要获得 IP 地址,您应该将系统连接到 WiFi(或 LAN)网络。

我已将 Apache 端口地址配置为其他内容,URL 如下所示

private static final String REGISTER_REQUEST_URL = "http://192.168.1.141:80/phptesting/Register.php";

其中端口号为80

【讨论】:

  • 老兄,我觉得你说实话。从来没有人告诉我使用 Apache 的端口,而不是 MySQL 的。我马上测试一下
  • 误报。它没有用。我使用了 Apache 端口和我的 IP 地址,但出现了错误。 "Unexpected response code 404 for" 然后它列出了 URL。
  • 如果Apache端口地址是80,可以省略80。如果是8080,使用8080。你的端口地址是什么?您需要使用我的答案中未使用的系统 IP 地址。确保使用 Postman 客户端可以通过 LAN 访问 URL(并且工作正常)。 404 表示您使用了错误的 URL,或者您尝试使用的服务不存在。
  • xampp 给了我 2 个 apache 端口供我使用。 80 和 443。我用的是 80。我正在使用我的 IP 地址(不难找到一个人的 IP 地址,但那是那个教程)。至于邮递员,我想如果我在机器上运行所有东西,它就会捡起来。但是邮递员听起来像是一个托管服务,我想先在本地运行所有东西。
  • 1) 确保 PHP 文件在 C:\xampp\htdocs\phptesting\&lt;all_of_your_php_files_for_this_project&gt; 下 2) 默认情况下跳过 URL 中的 80 它指向 Apache 3) Postman 没有托管服务它是我的朋友的 REST API 测试工具.这有助于我们测试 API 以确保其正常工作。
【解决方案2】:

这个Android: Volley NoConnectionError 将对你有所帮助。很可能您的 IP 地址和端口不正确。您可以通过在移动(模拟器)浏览器中输入IP地址和端口来检查它,然后检查它是否正确加载。如果没有为您的应用程序找到正确的 IP 地址和端口。

可以有模拟器和你的 xampp 服务器不在同一个网络中。您也可以尝试浏览移动地址中的 ip 地址和端口。

【讨论】:

  • 我已经调查过了,因此我的网址不是我的地址或本地主机。阅读 URL 旁边的注释行。另外,您对“在移动(模拟器)浏览器中输入 IP 地址和端口,然后检查它是否正确加载”感兴趣,我会怎么做?我可以将我的模拟器设置为在与我的计算机相同的 IP 地址上运行吗?这不就是 URL 应该做的吗?
  • no 您的模拟器从另一个端口启动。基本上去模拟器中的浏览器。然后输入 "10.0.2.2:3306/phptesting/Register.php" 。然后检查是否得到与在机器浏览器中运行时相同的输出
  • 你可以在Linux中检查你的rela ip地址:ifconfig [wlan0] 在Windows中使用:ipconfig
  • 当我在模拟器的浏览器中输入我的 php 文件的确切 url 时,浏览器立即开始下载一些东西,但随后停止了。我猜它发现 PHP 文件没问题。
  • 在你的 noram 机器浏览器中也做同样的事情?
猜你喜欢
  • 2012-10-23
  • 2011-06-28
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2017-06-16
  • 2014-11-06
  • 2014-02-11
相关资源
最近更新 更多