我正在尝试编写一个需要用户创建帐户的简单应用。我决定使用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;
这是android代码。我正在使用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;
}
这种组合导致崩溃。我已经验证了请求到达服务器。任何人都可以提供一些见解吗?
答案 0 :(得分:0)
尝试
header('Content-type: application/json');
echo json_encode($master);