我有以下PHP代码:
public function remote_login() {
if($this->isAjax()) {
$username = $_POST['username'];
$password = $_POST['password'];
$result = $this->db->prepTemplate("SELECT token, password FROM User WHERE username = ?",'s',array($username), SqlTemplates::RFQ);
$validate = $this->getSecurity()->validate($password, $result['password'], '5.4');
if($validate) {
print json_encode($result['token']);
}
}
else {
return false;
}
}
使用android我试图通过以下方式读取JSON:
public String sendToServer(List<NameValuePair> pair, String url){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
try {
throw new Exception(response.getStatusLine().getReasonPhrase());
} catch (Exception e) {
e.printStackTrace();
}
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
Log.i("Test det her", sb.toString());
return sb.toString();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Error";
}
如您所见,我记录字符串结果并获得以下输出:
01-21 19:46:51.512 1239-1256/dk.anapp.notebox I/Test det her﹕ [ 01-21 19:46:51.522 1239: 1256 W/dalvikvm ]
这显然是错误的!
谁能告诉我发生了什么?或者我做错了什么?
控制台日志
01-21 19:56:59.002 1339-1356/dk.anapp.notebox I/Test det her﹕ [ 01-21 19:56:59.002 1339: 1356 W/dalvikvm ]
threadid=11: thread exiting with uncaught exception (group=0xb1a25b90)
01-21 19:56:59.012 1339-1356/dk.anapp.notebox E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: dk.anapp.notebox, PID: 1339
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.UnsupportedOperationException: JsonNull
at com.google.gson.JsonElement.getAsString(JsonElement.java:191)
at logic.HTTPReciver.is_auth(HTTPReciver.java:37)
at dk.anapp.notebox.Mediator.is_auth(Mediator.java:52)
at dk.anapp.notebox.Login$1.doInBackground(Login.java:45)
at dk.anapp.notebox.Login$1.doInBackground(Login.java:41)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
**网址**
“http://notebox.dk/User/remote_login”
is_auth方法
public Boolean is_auth(String username, String password){
List<NameValuePair> pair = new ArrayList<NameValuePair>(3);
pair.add(new BasicNameValuePair("request","ajax"));
pair.add(new BasicNameValuePair("username",username));
pair.add(new BasicNameValuePair("password",password));
JsonElement root = new JsonParser().parse(sender.sendToServer(pair, "http://notebox.dk/User/remote_login"));
if(root.getAsString() != null || root.getAsString() != "Error"){
setToken(root.getAsString());
return true;
}else{
return false;
}
}
答案 0 :(得分:1)
我没有直接回答你的问题。但我发现你可以大量简化代码,也许可以找到错误的代码。
首先,对于您的网络服务,我建议您使用Redbean。它是一个非常强大且易于使用的PHP ORM库。
然后,为了从Android进行http查询,我总是使用AsyncHttpClient。因此,您可以忘记线程化您的请求以及您必须记住的其他详细信息。
最后,如果您希望在解析json时轻松生活,我强烈建议您使用Gson库。
使用这3个工具,您的应用和网络服务将像魅力一样工作,您的代码看起来非常专业;)
答案 1 :(得分:1)
http://www.php.net/manual/en/function.json-encode.php中的所有示例都显示json_encode()将数组作为参数,而不是字符串。也许这就是你问题的来源。
请尝试:
print json_encode(array("token" => $result['token']));
或简单地说:
print json_encode(array($result['token']));
如果这不起作用,请尝试在json_encode()函数中传递硬编码字符串,并查看它在Android应用中的响应中的显示效果。