У меня есть следующий PHP код:Странный результат на json_encode
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;
}
}
С андроида Я пытаюсь читать 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)
** URL-адрес **
"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;
}
}
Каков ожидаемый результат? я понятия не имею, как выглядит токен, и насколько я понимаю, это строка, которую вы построили. – Ohgodwhy
: токен выглядит следующим образом: gTWcn8zs Итак, результат должен быть: gTWcn8zs –
Кажется, что он ничего не возвращает, вы уверены, что $ this-> isAjax() и $ validate верны? –