【问题标题】:Php fails to return JSON array to Android appPHP 无法将 JSON 数组返回到 Android 应用程序
【发布时间】:2014-03-09 14:32:05
【问题描述】:

我正在尝试编写一个需要用户创建帐户的简单应用程序。我决定使用 mysql / php 作为后端和 Android 来创建实际的应用程序。用户可以从应用程序输入他们的用户名和密码,后端会将其存储在数据库中。然后,一个 json 数组将返回给应用程序。不幸的是,我拥有的代码不起作用。应用程序崩溃了,日志上没有打印任何内容。

这是PHP:

$json = array();
$master = array();
$json['status'] = "fail";
$json['message'] = "unable to connect to the server";
$master['master'] = $json;
echo json_encode($master);
exit;

这里是安卓代码。我正在使用 AsyncTask 类来进行网络连接。这是完成工作的函数:

    protected Void doInBackground(String... urls)
    {
        HttpPost httppost = new HttpPost(urls[0]);
        BufferedReader reader = null;

        try
        {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            nameValuePairs.add(new BasicNameValuePair("method", "create"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = Client.execute(httppost);

            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                // Append server response in string
                sb.append(line + "");
            }

             // Append Server Response To Content String lol
            Content = sb.toString();
        }
        catch(Exception ex)
        {
            Error = ex.getMessage();
        }
        finally
        {
            try
            {
                reader.close();
            }
            catch(Exception ex) 
            {

            }
        }

        return null;
    }

这种组合会导致崩溃。我已验证请求已到达服务器。谁能提供一些见解?

【问题讨论】:

  • “无法连接到服务器”来自服务器,****警察..

标签: php android json http


【解决方案1】:

试试

header('Content-type: application/json');
echo json_encode($master);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多