如何处理android中json帖子的响应

时间:2017-02-06 14:27:41

标签: android json

我正在尝试构建一个应用程序,您需要通过JSON帖子并基于响应$response['success']$response['error']对我的网络服务器进行身份验证。网络服务器是PHP,我知道POST正确进入,我遇到的问题是阅读响应。现在我使用以下代码,它给了我一个错误:

Java代码(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必须为true,在任何其他情况下都为false。

错误

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文件

<?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);

}

希望有人可以帮助我!

1 个答案:

答案 0 :(得分:1)

试试这个..

    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");

实际上你是以对象形式获得它,但是解析为Array。