Sgotenks
Sgotenks

Reputation: 1733

Java: how to check the content of a php script output?

sorry for the stupid question but my knowledge of java net is terrible. BAsically in my android application a call many php scripts to get data from a mysql db. These data are returned in json format and i use Google json library to parse them. Everything works fine but know in each php page i have to add a test. It the test is successfull, then the script continues and returns the json file, but if the test fails, the script return the string "false", or the value false (that's up to me) and my application instead of showing data has to redirect the user to a login page.

The code is the following:

        URL url = new URL(Costanti.IP_SERVER+"myApps.php"+"?userId="+this.userId);
        try 
        {

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            int status = conn.getResponseCode();
            if (status >= 200 && status <= 299)
            {
                Reader r = new InputStreamReader(conn.getInputStream());
                Applicazioni dati = new Applicazioni();
                try 
                {

                    dati = gsonReader.fromJson(r, Applicazioni.class);

                    return dati;
                } 
                catch (Exception e) 
                {
                    System.out.println("Ho fallito a prendere i dati");
                    Log.e("JSON_Parser",e.toString());

                }
            }   
        } 
        catch (IOException e) 
        {
            System.out.println("Ho fallito la connnection");
            e.printStackTrace();
        }
    } 

So basically i use this google library to read the json file inside the imputStreamReader and fill the Applicazioni object with my data.

How can i check if the content of the imputStreamReader is the string "false" or the boolean false and if it's different parse it with the json library????

In the php at the end i do echo json_encode($applicazione); in one case or echo "false" in the other case Tnx

Upvotes: 0

Views: 156

Answers (2)

kgautron
kgautron

Reputation: 8283

InputStream in = new URL(url).openStream();
Scanner scanner = new Scanner(new InputStreamReader(in));
String result = scanner.useDelimiter("\\Z").next(); // this reads the whole
                                                    // script output in a string
if(result.equals("false"))
 handle the false value...
else
  dati = gsonReader.fromJson(result, Applicazioni.class);

Upvotes: 2

guru
guru

Reputation: 667

You can json encode the false result also like ["result"=>"false"] from PHP, This way you can always JSON decode in your Java program, and then look for result value.

You can put the result value in both cases in the output.

Upvotes: 1

Related Questions