首页 \ 问答 \ 从Php获取Android中的Json(Get a Json in Android from Php)

从Php获取Android中的Json(Get a Json in Android from Php)

我从php创建一个Json对象如下:

<?php
if (isset($_POST["name"]) ) { 
    $name = mysqli_real_escape_string( $connnection, $_POST['name'] );

    //Json response
    $response["myarray"] = array();
    $product = array();
    $product["name"] = $name;
    array_push($response["myarray"], $product);
    echo json_encode($response);        
    }
?>

(PHP文件有其他功能,它们已经正常工作)

我试图使用放在onCreate类中的代码从Android设备获取此json:

        Intent vii = getIntent();
        uniqid = vii.getStringExtra("Content");

        final Context context = this;
        AsyncTask<Void,Void,Void> mQRCheckTask = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                // Register on our server
                // On server creates a new user
                try {
                    jObj=QRCheck(context, uniqid);
                    return null;
                } finally {

                }

            }

            @Override
            protected void onPostExecute(Void result) {
                try {
                    ITEMS = jObj.getJSONArray(TAG_ITEMS);
                    JSONObject infoUser = ITEMS.getJSONObject(0);
                    // Storing each json item in variable
                    String SUCCESS = infoUser.getString(TAG_SUCCESS);
                    String name = infoUser.getString(TAG_NAME);
                    String mail = infoUser.getString(TAG_MAIL);
                    Log.d(TAG_NAME, mail+name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //mQRCheckTask = null;

            }

        };
        mQRCheckTask.execute(null, null, null);
        //END CONNECT TO INTERNET!!

    }

QRCheck功能如下

public static JSONObject QRCheck(final Context context, String QRid) {
        Log.i(TAG, "registering device");
        String serverUrl = myURL;
        Map<String, String> params = new HashMap<>();
        params.put("uniqid", QRid);
        //params.put("expecting", expecting);
        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        try {

            return jObj=post(serverUrl, params);
        }
        catch (IOException e) {
            Log.e(TAG, "Failed to register on attempt");
            try {
                Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Log.d(TAG, "Thread interrupted: abort remaining retries!");
                Thread.currentThread().interrupt();
                return null;
            }
            // increase backoff exponentially
            backoff *= 2;
        }
        Log.d(TAG, "Nothing Posted");
        return null;
    }


public static JSONObject post(String endpoint, Map<String, String> params)
            throws IOException {

        URL url;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        try {
            Log.d("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            //conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        //See the Answer in LogCat
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        Log.i(TAG, "This is the answer: "+String.valueOf(response));
        json = response.toString();

        //print result
        System.out.println(response.toString());
        Log.d("JSON Parser", json);
        // try parse the string to a JSON object
        try {
             return jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    }

我得到以下LogCat

I/alvaro﹕ registering device
V/alvaro﹕ Posting 'uniqid=56a12474923df' to http://www.blabal.checkQR.php
D/URL﹕ > http://www.blabal.checkQR.php
E/alvaro﹕ Failed to register on attempt
D/alvaro﹕ Sleeping for 2446 ms before retry
D/alvaro﹕ Nothing Posted

当我执行Post命令时,它会输入if (isset($_POST["name"]) )并执行所有其他php函数,所以我知道php会正确回显json_encode($response)

我错过了正确接收Android上的json的东西,但我还没有设法看到它是什么...任何帮助将非常感谢!


I create a Json Object from php as follows:

<?php
if (isset($_POST["name"]) ) { 
    $name = mysqli_real_escape_string( $connnection, $_POST['name'] );

    //Json response
    $response["myarray"] = array();
    $product = array();
    $product["name"] = $name;
    array_push($response["myarray"], $product);
    echo json_encode($response);        
    }
?>

(The php file has other functions, which are already working fine)

I am trying to get this json from an android device using the code placed inside the onCreate class:

        Intent vii = getIntent();
        uniqid = vii.getStringExtra("Content");

        final Context context = this;
        AsyncTask<Void,Void,Void> mQRCheckTask = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                // Register on our server
                // On server creates a new user
                try {
                    jObj=QRCheck(context, uniqid);
                    return null;
                } finally {

                }

            }

            @Override
            protected void onPostExecute(Void result) {
                try {
                    ITEMS = jObj.getJSONArray(TAG_ITEMS);
                    JSONObject infoUser = ITEMS.getJSONObject(0);
                    // Storing each json item in variable
                    String SUCCESS = infoUser.getString(TAG_SUCCESS);
                    String name = infoUser.getString(TAG_NAME);
                    String mail = infoUser.getString(TAG_MAIL);
                    Log.d(TAG_NAME, mail+name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //mQRCheckTask = null;

            }

        };
        mQRCheckTask.execute(null, null, null);
        //END CONNECT TO INTERNET!!

    }

And the QRCheck function is the following

public static JSONObject QRCheck(final Context context, String QRid) {
        Log.i(TAG, "registering device");
        String serverUrl = myURL;
        Map<String, String> params = new HashMap<>();
        params.put("uniqid", QRid);
        //params.put("expecting", expecting);
        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        try {

            return jObj=post(serverUrl, params);
        }
        catch (IOException e) {
            Log.e(TAG, "Failed to register on attempt");
            try {
                Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Log.d(TAG, "Thread interrupted: abort remaining retries!");
                Thread.currentThread().interrupt();
                return null;
            }
            // increase backoff exponentially
            backoff *= 2;
        }
        Log.d(TAG, "Nothing Posted");
        return null;
    }


public static JSONObject post(String endpoint, Map<String, String> params)
            throws IOException {

        URL url;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        try {
            Log.d("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            //conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        //See the Answer in LogCat
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        Log.i(TAG, "This is the answer: "+String.valueOf(response));
        json = response.toString();

        //print result
        System.out.println(response.toString());
        Log.d("JSON Parser", json);
        // try parse the string to a JSON object
        try {
             return jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    }

And I get the Following LogCat

I/alvaro﹕ registering device
V/alvaro﹕ Posting 'uniqid=56a12474923df' to http://www.blabal.checkQR.php
D/URL﹕ > http://www.blabal.checkQR.php
E/alvaro﹕ Failed to register on attempt
D/alvaro﹕ Sleeping for 2446 ms before retry
D/alvaro﹕ Nothing Posted

WhenI execute the Post command it enters the if (isset($_POST["name"]) ) and does all the other php functions, so I know that the php echoes correctly the json_encode($response).

I am missing something to receive correctly the json on android, but I haven't managed to see what it is... Any help would be really appreciated!


原文:https://stackoverflow.com/questions/34932939
更新时间:2022-08-23 16:08

最满意答案

最后想出了一个相当简单的解决方案。 每次填充数组后,我都会在datepicker上调用refresh方法。

$.each(data.response, function(i, item) {
    disableddates.push(item);
});

// end array population

$( "#datepicker" ).datepicker( "refresh" );

Finally figured out a rather simple solution. I called refresh method on the datepicker after the array is populated, every time.

$.each(data.response, function(i, item) {
    disableddates.push(item);
});

// end array population

$( "#datepicker" ).datepicker( "refresh" );

相关问答

更多
  • 我想出了这个问题。 我将#date_end值的minDate设置为#date_start的当前值。 因此,它会自动将日期选择更改为#date_start中最后一个选定日期的最新可用日期。 因此,为了解决这个问题,我只需在尝试更改#date_end之前更改minDate。 新代码: