将JSON从PHP发布到Android问题

将JSON从PHP发布到Android问题,php,android,json,Php,Android,Json,您好,我目前在从PHP向Android设备发送JSON对象时遇到问题。 我以前和另一个人这样做过,效果很好,但现在似乎不起作用 这是一个简单的登录脚本。它应该根据输入的登录电子邮件和密码是否正确返回用户数据或“false” 在浏览器中尝试时可以看到响应,但据我的同事说,他在android开发机器上查看时得到的是一个空数组 这是php代码: <?php include('config.php'); include('functions.php'); include('

您好,我目前在从PHP向Android设备发送JSON对象时遇到问题。 我以前和另一个人这样做过,效果很好,但现在似乎不起作用

这是一个简单的登录脚本。它应该根据输入的登录电子邮件和密码是否正确返回用户数据或“false”

在浏览器中尝试时可以看到响应,但据我的同事说,他在android开发机器上查看时得到的是一个空数组

这是php代码:

<?php
    include('config.php');
    include('functions.php');
    include('password_hash_lib/password.php');

    if (!isset($_REQUEST["device"]))
    {
        $Email = $_POST['Email'];
        $Password = $_POST['Password'];
        try
        {
            if (authenticate($Email, $Password))
            {
                echo "true";
            }
            else {
                echo "false";
            }
        }
        catch (Exception $e)
        {
            echo $e->getMessage();
        }
    }
    else if (isset($_REQUEST["device"]))
    {
        $device = $_REQUEST['device'];
        $Email = $_REQUEST['email'];
        $Password = $_REQUEST['password'];

        if ($device == 'mobi')
        {   
            try
            {
               if (authenticate($Email, $Password))
               {
                  $curruser = explode("+", $_SESSION['sess_user_auth']);

                  $arr = new ArrayObject(Array(), ArrayObject::STD_PROP_LIST);  
                  $arr->userid = $curruser[0];
                  $arr->email = $curruser[1];
                  $arr->fullname = $curruser[2];
                  $arr->displaypic = $curruser[3];
                  $arr->displayname = $curruser[4];

                  echo str_replace("\\", "", json_encode((object) $arr));        
               }
               else {
                  echo "false";
               }
            }
            catch (Exception $e)
            {
               echo $e->getMessage();
            }
        }
    }

?>

我曾尝试在代码中使用return而不是echo,但仍然不起作用。没有错误,只有一个空数组。

Replace:
echo str\u Replace(“\\”,“”,json\u encode((object)$arr))


这样:
echo json_encode(数组('user'=>$arr))

这应该可以解决您的问题。尽量在脚本返回的内容上保持一致。即使失败,它也必须始终返回相同类型的数据(
JSON

<?php
include('config.php');
include('functions.php');
include('password_hash_lib/password.php');

if (!isset($_REQUEST["device"]))
{
    $Email = $_POST['Email'];
    $Password = $_POST['Password'];
    try
    {
        if (authenticate($Email, $Password)) echo json_encode(array('auth' => true));
        else echo json_encode(array('auth' => false));
    }
    catch (Exception $e)
    {
        echo json_encode(array('error' => $e->getMessage()));
    }
}
else if (isset($_REQUEST["device"]))
{
    $device = $_REQUEST['device'];
    $Email = $_REQUEST['email'];
    $Password = $_REQUEST['password'];

    if ($device == 'mobi')
    {
        try
        {
            if (authenticate($Email, $Password))
            {
                $curruser = explode("+", $_SESSION['sess_user_auth']);

                $json = array();
                $json['userid'] = $curruser[0];
                $json['email'] = $curruser[1];
                $json['fullname'] = $curruser[2];
                $json['displaypic'] = $curruser[3];
                $json['displayname'] = $curruser[4];
                echo json_encode($json);        
            }
            else
            {
                echo json_encode(array('auth' => false));
            }
        }
        catch (Exception $e)
        {
            echo json_encode(array('error' => $e->getMessage()));
        }
    }
}

我有一个类似的问题,我将HttpGet改为HttpPost,它成功了。希望这有帮助

为什么要从json_编码中删除反斜杠?因为返回的数组中有一个url,json_编码似乎会添加反斜杠以转义某些字符。但它不再是有效的json。您无法再对其进行解码。@blank:不要弄乱JSON。您从未直接修改json字符串,因为您所做的是引入javascript语法错误。您好,我尝试了您的所有建议,但没有一个对我有效。我刚刚编辑了我的帖子,并按照您的要求添加了android脚本。谢谢您,我会尝试的,你能告诉我你犯了哪些错误,你是如何改正的,为什么?这样他们就不会再发生了。:)读取服务器响应时,必须在
readLine
上循环,在代码中只读取一次。另外,您连续分析了
json
3或4次。
<?php
include('config.php');
include('functions.php');
include('password_hash_lib/password.php');

if (!isset($_REQUEST["device"]))
{
    $Email = $_POST['Email'];
    $Password = $_POST['Password'];
    try
    {
        if (authenticate($Email, $Password)) echo json_encode(array('auth' => true));
        else echo json_encode(array('auth' => false));
    }
    catch (Exception $e)
    {
        echo json_encode(array('error' => $e->getMessage()));
    }
}
else if (isset($_REQUEST["device"]))
{
    $device = $_REQUEST['device'];
    $Email = $_REQUEST['email'];
    $Password = $_REQUEST['password'];

    if ($device == 'mobi')
    {
        try
        {
            if (authenticate($Email, $Password))
            {
                $curruser = explode("+", $_SESSION['sess_user_auth']);

                $json = array();
                $json['userid'] = $curruser[0];
                $json['email'] = $curruser[1];
                $json['fullname'] = $curruser[2];
                $json['displaypic'] = $curruser[3];
                $json['displayname'] = $curruser[4];
                echo json_encode($json);        
            }
            else
            {
                echo json_encode(array('auth' => false));
            }
        }
        catch (Exception $e)
        {
            echo json_encode(array('error' => $e->getMessage()));
        }
    }
}
@Override
protected Boolean doInBackground(Void... params)
{
    boolean status = false;
    LoginMgr lmgr = new LoginMgr(getSherlockActivity().getBaseContext());
    try
    {
        // Connect to the remote server
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://www.xxxxx.com/login.php?device=mobi&email=xxxxxx@gmail.com&password=xxxxxxx");
        HttpResponse response = httpclient.execute(httpget);
        int statuscode=response.getStatusLine().getStatusCode();
        if(statuscode==200)
        {
            // Read response
            InputStream is = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            final StringBuilder stringbuild= new StringBuilder();
            String curr_line = null;
            while ((curr_line = br.readLine()) != null)
            {
                stringbuild.append(curr_line);
            }

            getSherlockActivity().runOnUiThread(new Runnable() {
                @Override
                public void run()
                {
                    Toast.makeText(getSherlockActivity(), stringbuild.toString(), Toast.LENGTH_LONG).show();    
                }
            });

            // Parse response to JSON
            JSONObject json = new JSONObject( stringbuild.toString() );
            if (json.has("auth"))
            {
                if (json.getBoolean("auth"))
                {
                    // Authentificate with success
                    getSherlockActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            Toast.makeText(getSherlockActivity(), "Success", Toast.LENGTH_LONG).show();    
                        }
                    });
                }
                else
                {
                    // In this case, authentification has failed
                    getSherlockActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run()
                        {
                            Toast.makeText(getSherlockActivity(), "Wrong user credentials", Toast.LENGTH_LONG).show();    
                        }
                    });
                }
            }
            else if (json.has("userid"))
            {
                String userid = json.getString("userid");
                String email = json.getString("email");
                String fullname = json.getString("fullname");
                String displaypic = json.getString("displaypic").replace("\\/","/");
                String displayname = json.getString("displayname");

                // In this case, we got some data about the user
                String image = "http://www.xxxxx.com/img/timthumb.php?&h=50&w=50&src=" + displaypic;
                lmgr.loginUser(new Login(json.getString("0"), json.getString("4"), json.getString("1"), image));
                status = true;
                JSONObject job = new JSONObject(jsonstr);
                if(job.getString("success").equalsIgnoreCase("1"))
                {
                    lmgr.loginUser(new Login(userid, fullname, email, displaypic));
                    status = true;
                }
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return status;
}