JSON 来自 PHP 脚本的响应

JSON response from PHP script

我正在为 Android 构建注册系统。我可以向数据库中添加数据,这很好。现在我想添加一些 JSON 来通知用户注册成功或出现不同的错误。即

{
  "status":"success",
  "message":"Successful Registration"

}

 {
  "status":"fail",
  "message":"Please enter your name"

}

等等

这是我的 php 脚本。

<?php
   require "init.php";
   $j = new stdClass();
   $name = $_POST['name'];
   $user_name = $_POST['user_name'];
    $user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
    if(!$name){
    json_encode(array('status' => 'fail', 'message' => 'Please enter your    
    name'));
   }
   $sql_query = "insert into user_info    
  values('$name','$user_name','$user_pass');";

   if(mysqli_query($con,$sql_query)){

    json_encode(array('status' => 'success', 'message' => 'Successfully 
    registered'));

  }else{

   json_encode(array('status' => 'fail', 'message' => 'Could not   
   register'));
  }



 ?>

使用这个脚本我无法从我的 Java 代码中检测到任何 JSON 响应,即使我成功添加了数据。

  private void registerUser(final String name, final String userName,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";


    StringRequest strReq = new StringRequest(Request.Method.POST,
            "MY_LINK_GOES_HERE", new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d("Response", "Register Response: " + response.toString());

            Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

            // Launch login activity
            Intent intent = new Intent(
                    Register.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("user_name", userName);
            params.put("user_pass", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Log.d("Response", "Register Response: " + response.toString());

什么也没给我。

有什么想法吗?

谢谢。

首先,你应该在你的问题中提到你正在使用 android-volley 库,或者至少使用 tag。其次,如果您正在尝试解析 JSON 响应,那么您应该使用 JsonObjectRequest 实例来执行此操作。假设您的 php 脚本发送正确的 JSON,您可以尝试使用 volley 进行一些简单直接的操作,例如:

JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    response = response.getJSONObject("args");
                    String site = response.getString("site"), network = response.getString("network");
                    View view = findViewById(R.id.activity_layout);
                    Snackbar.make(view, "Site : " + site + " Network : " + network, Snackbar.LENGTH_INDEFINITE).show();
                } catch (JSONException e) {
                    Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getBaseContext(), "Error Listener", Toast.LENGTH_LONG).show();
            }
        });

        Volley.newRequestQueue(this).add(jsonRequest);

假设您的 JSON 是这样的:

{
  "args": {
    "network": "somenetwork", 
    "site": "code"
  }, 
  "args2": {
    ...
  }, 
  "args3": "...", 
  "args4": "..."
}

现在,根据您发送的 JSON,您可以尝试任何组合。您也可以查看这个非常有用的 tutorial。希望这可以帮助。如果您需要更多帮助,请告诉我。

我在尝试注册时在我的应用程序中遇到了同样的问题。我想检查用户是否注册以及用户名是否可用。

所以我所做的是:

PHP 文件:

<?php
try {
    $handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}

$username = $_POST['username'];
$password=$_POST['password'];
$email = $_POST['email'];
$dateCreated = $_POST['dateCreated'];
$android_version= $_POST['android_version'];
$api_level = $_POST['api_level'];
$check = $handler->query("SELECT * FROM table WHERE username = '$username'");
$don = array();
     if($check->rowCount() > 0){
          $don = array('result' =>TRUE);
          die();
     }else{
          $don = array('result' =>FALSE);
          $handler->query("INSERT INTO table(id, username, password, email, dateCreated, activated, Android_Version, API_Level) VALUES('', '$username','$password','$email', '$dateCreated', 0, '$android_version', '$api_level')");
     }

echo json_encode($don);
?>

Android:

私有 class MyInsertDataTask 扩展了 AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(YourActivity.this);
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setIndeterminate(true);
        pDialog.setMessage(getString(R.string.dialog_rate_data_submit));
        pDialog.setCancelable(false);
        pDialog.setInverseBackgroundForced(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("username", uName));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        nameValuePairs.add(new BasicNameValuePair("email", email));
        nameValuePairs.add(new BasicNameValuePair("dateCreated", date));
        nameValuePairs.add(new BasicNameValuePair("android_version", release));
        nameValuePairs.add(new BasicNameValuePair("api_level", String.valueOf(sdkVersion)));

        try
        {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(AppConstant.REGISTER_URL);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpClient.execute(httpPost);
            httpEntity = response.getEntity();
            is = httpEntity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            Log.e("Responce", result.toString());
            if (result != null) {
                data = new JSONObject(result.toString());
                usernameExists = data.getBoolean("result");
            }
        }
        catch(Exception e)
        {
            Log.e("Fail 1", e.toString());
        }
        return  usernameExists;
    }
    @Override
    protected void onPostExecute(Boolean aVoid) {
        super.onPostExecute(aVoid);
        pDialog.dismiss();
        if (aVoid){
            Snackbar.with(YourActivity.this).type(SnackbarType.MULTI_LINE).text(getString(R.string.username_exists_message)).color(Color.parseColor(AppConstant.ENABLED_BUTTON_COLOR)).show(getActivity());
        }else {
            Toast.makeText(YourActivity.this, getString(R.string.created_successfully), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(YourActivity.this, MainActivity.class);
            startActivity(intent);
            YourActivity.this.finish();
        }

    }
}

结果是,如果用户名存在,则弹出一条消息说用户名已经存在,否则用户注册

结果:

我修好了!这是一个 php 问题。这是我的解决方案。

<?php
  require "init.php";
  header('Content-type: application/json');
  $name = $_POST['name'];
  $user_name = $_POST['user_name'];
  $user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);

        $sql_query = "select * from user_info WHERE user_name  
  ='".mysqli_real_escape_string($con, $user_name)."'";

        $result = mysqli_query($con, $sql_query);   

        $results = mysqli_num_rows($result);

        if ($results){
            $don = array('result' =>"fail","message"=>"Username exists. User               
        a different one");
        }else{

            $sql_query = "insert into user_info  
       values('$name','$user_name','$user_pass');";

            if(mysqli_query($con,$sql_query)){

            $don = array('result' =>"success","message"=>"Successfully  
            registered!Well done");

            }
        }

    echo json_encode($don);

  ?>