从 php 返回的 Android 读取数组

域“A”包括来自域“B”的图像


<img src="https://DOMAIN_B/basic-auth/protected_image/secure.jpg">


域“B”具有基本的 HTTP 身份验证。


<?php

    header("HTTP/1.1 401 Unauthorized");

    header("WWW-Authenticate: Basic realm='Please login'");

    exit;

?>

我的问题是为什么域“A”上没有出现登录弹出窗口。Chrome 给出错误“401 未授权”。但从技术上讲,浏览器应该会在域“A”上弹出登录显示。另一方面,本地和https://jsfiddle.net/w493nnp9/18/一切正常。


您可以访问此链接,页面显示登录弹出窗口。但是为什么其他域不显示。 https://jsfiddle.net/w493nnp9/18/我正在阅读 android 方法中的 php 响应。


PHP


 if(mysqli_num_rows($result)>0) {

        $status = "Success!";

        echo "Success!";

    } else {

        echo "Login failed";

    }

安卓


@Override

    protected void onPostExecute(String result) {

        if(result.equals("Success!")) {

            Toast.makeText(context, "Login Successful!", Toast.LENGTH_LONG).show();

            Intent goToWelcomePage = new Intent(context, welcome.class);

            context.startActivity(goToWelcomePage);

        } else if (result.equals("User Created")){

            Toast.makeText(context, "User Created.  Login Now.", Toast.LENGTH_LONG).show();

            Intent goToLoginPage = new Intent(context, MainActivity.class);

            context.startActivity(goToLoginPage);

        } else {

            Toast.makeText(context, result, Toast.LENGTH_LONG).show();

        }

    }

上面的脚本可以正常工作。


但是,我想读取一个结果数组。我在 PHP 中试过这个。


$status = array();


if(mysqli_num_rows($result)>0) {

    $status = "Success!";

    echo json_encode(array("result"=>$status,"name"=>$username));   

} else {

    $status = "Login failed";

    echo json_encode(array("result"=>$status));

}

不知道如何在 Android 中阅读。此外,我不确定上述 php 是否是将结果返回给 android 的正确方法。


蓝山帝景
浏览 131回答 1
1回答

鸿蒙传说

PHP代码没有问题,至少它可以返回一个正确的json,如果你想要的是:{"result":"Success!","name":"YOUR_LOGIN_NAME"}或者{"result":"Login failed"}在 Android 中,您应该使用 json 解析器库来解析“结果”,例如 Gson(https://github.com/google/gson)。您可以创建一个响应类,例如:class MyResponse {&nbsp; &nbsp; String result;&nbsp; &nbsp; String name;}然后你可以简单地调用你的代码:@Overrideprotected void onPostExecute(String result) {&nbsp; &nbsp; Gson gson = new Gson();&nbsp; &nbsp; MyResponse response = gson.fromJson(result, MyResponse.class);&nbsp; &nbsp; switch (response.result) {&nbsp; &nbsp; &nbsp; &nbsp; case "Success!":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do something when login success&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // can call response.name here to read the login name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case "Login failed":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do something when login failed&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; // and more...&nbsp; &nbsp; }如果您对现代 HTTP 客户端感兴趣,可以看看:okhttp ( https://github.com/square/okhttp )改造 ( https://github.com/square/retrofit )
打开App,查看更多内容
随时随地看视频慕课网APP