S.Holzhauer S.Holzhauer - 4 years ago 122
JSON Question

How to handle the response to a json post in android

I am trying to build an app where you need the authentication happens against my webserver trough a JSON post and based on the response

$response['success']
or
$response['error']
. The webserver is PHP and I know the POST is coming in correctly, what I am having trouble with is reading the response. Right now I am using the following code and it gives me an error:

Java code (app)

protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.


OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
boolean returnvalue = false;
try {
// Simulate network access.
// TODO: send username/password to https://svlo.scoutingvictorie.nl/android.php
// if return == true login
// else error.
// constants
URL url = new URL("https://victorie.stienos.nl/android.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("action", "LogIn");
jsonObject.put("username", mEmail);
jsonObject.put("password", mPassword);
String message = jsonObject.toString();

conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);

//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

//open
conn.connect();

//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();

// do something with response
is = conn.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
String text = null;

reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("success")) {
text = reader.nextString();
if(text.equals('1')){
returnvalue = true;
}
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();

// String contentAsString = readIt(is,len);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}


/*
finally {
//clean up
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}

conn.disconnect();
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}*/

return returnvalue;
}


returnvalue
needs to be true if the response is success, false in any other case.

Error

02-06 15:18:11.194 5037-5201/nl.stienos.svlo E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: nl.stienos.svlo, PID: 5037
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
at android.util.JsonReader.expect(JsonReader.java:310)
at android.util.JsonReader.beginArray(JsonReader.java:277)
at nl.stienos.svlo.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:360)
at nl.stienos.svlo.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:303)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 


PHP file

<?php

include_once 'backend/functions/android_app.php';

error_log("JSON SUCCESS");
$json = file_get_contents('php://input');
$obj = json_decode($json);
$action = $obj->{'action'};

$response = array();

if($action == 'LogIn'){
$username = $obj->{'username'};
$password = $obj->{'password'};

if(AppLogIn($username, $password)){
$response["success"] = 1;
}
else{
$response["error"] = 1;
}
echo json_encode($response);

}


Hope someone can help me!

Answer Source

try this..

    BufferedReader in = new BufferedReader(new  InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String bufferString = response.toString();

        JSONObject json = new JSONObject(bufferString);
        String success = json.getString("success");

Actually you are getting it in object form, but parsing as Array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download