首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android JSON,其中Volley和PHP的输入结尾为

Android JSON,其中Volley和PHP的输入结尾为
EN

Stack Overflow用户
提问于 2018-07-31 11:52:04
回答 1查看 324关注 0票数 1

我正在编写一个应用程序,需要使用存储在数据库中的联系人,所以我正在使用wammp和PHPMyAdmin来编写一个简单的REST API。我已经编写了涉及注册和登录的部分,但由于某些原因,我无法让联系人的存储工作,即使我认为这几乎是一样的事情逐字。我得到了一个异常:

代码语言:javascript
复制
org.json.JSONException: End of input at character 0 of

我到处寻找这个问题,看起来我传递回我的应用程序的JSON是空的,所以我意识到了这个问题,但无论在哪里,解决方案都没有帮助我解决这个问题,所以我觉得这可能是一个独特的问题。以下是我的相关Android代码:

代码语言:javascript
复制
// Create the new string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_NEW_CONTACT, new Response.Listener<String>()
{
    @Override
    public void onResponse(String response)
    {
        // Log method entry
        MethodLogger methodLogger = new MethodLogger();

        // Log the JSON that was returned
        methodLogger.d("New Contact Response: " + response.toString());

        // Remove the processing view
        hideDialog();

         // Try to retrieve JSON and parse through it
         try
         {
             JSONObject jObj = new JSONObject(response);

             // Check for errors in the JSON passed back
             boolean error = jObj.getBoolean("error");

             /*----------------------------------------------------------------*
              *  If there was no error found                                   *
              *----------------------------------------------------------------*/
              if (!error)
              {
                  // Indicate the success to the user
                  Toast.makeText(getApplicationContext(), "Contact successfully created.", Toast.LENGTH_LONG).show();

                  // Take the user back to the contact page
                  routeToContactPage();
              }

              /*----------------------------------------------------------------*
               *  Else if there was an error found                              *
               *----------------------------------------------------------------*/
               else
               {
                   // Notify the user
                   String errorMsg = jObj.getString("message");
                   Toast.makeText(getApplicationContext(),
                                      errorMsg, Toast.LENGTH_LONG).show();
               }
            }

            /*--------------------------------------------------------------------*
             * Catch any error in retrieving parsing etc JSON                     *
             *--------------------------------------------------------------------*/
             catch (JSONException e)
             {
                 e.printStackTrace();
                 Toast.makeText(getApplicationContext(), "Error storing contact: " + e.getMessage(), Toast.LENGTH_LONG).show();
             }

             // Log method exit
             methodLogger.end();

         }
     }, new Response.ErrorListener()
     {
         @Override
         public void onErrorResponse(VolleyError error)
         {
              // Log method entry
              MethodLogger methodLogger = new MethodLogger();

              // Notify the user
              methodLogger.e("Error storing contact: " + error.getMessage());
              Toast.makeText(getApplicationContext(),
                                     error.getMessage(), Toast.LENGTH_LONG).show();
              hideDialog();

              // Log method exit
              methodLogger.end();
          }

      })
      {
           @Override
           protected Map<String, String> getParams()
           {
               // Log method entry
               MethodLogger methodLogger = new MethodLogger();

               // create a new params object and add the contact data
               Map<String, String> params = new HashMap<String, String>();

               // Add the params to the volley request
               params.put("user_id", SessionManager.getUser().getId());
               params.put("name", name);
               params.put("email", emailAddress);

               // Log method exit
               methodLogger.end();

               // Return the user data
               return params;
           }

      };

      // Send the request string to the request queue to be sent to the PHP API
      AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}

相关PHP代码:

存储联系人:

代码语言:javascript
复制
public function storeContact($name, $email, $user_id) 
{
    $uuid = uniqid('', true);

    $result = mysqli_query($this->conn, "INSERT INTO contacts (unique_id, name, email, created_at, updated_at, user_id) VALUES ('$uuid', '$name', '$email', NOW(), NULL, '$user_id')") or die (mysql_error());

    if ($result) 
    {
        $contact = mysqli_query($this->conn, "SELECT * FROM contacts WHERE name = '$name' AND user_id = '$user_id'");

        return $contact;
    } 
    else 
    {
        return false;
    }
}

与服务器/应用程序通信:

代码语言:javascript
复制
<?php

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

$response = array();

if (isset($_POST['user_id']) && isset($_POST['name']) && isset($_POST['email'])) 
{
    $user_id = $_POST['user_id'];
    $name = $_POST['name'];
    $email = $_POST['email'];

    $result = $db->storeContact($name, $email, $user_id); 

    if ($result) 
    {
        $response["error"] = FALSE;
        $response["message"] = "Contact stored successfully";
    } 
    else 
    {
        $response["error"] = TRUE;
        $response["message"] = "Unknown error occurred in storing contact";
    }
} 
else 
{
    $response["error"] = TRUE;
    $response["message"] = "Required parameters, name, email, or user_id, missing";
}

echo json_encode($response);

?>

最后,相关的logcat输出:

代码语言:javascript
复制
07-30 22:39:07.408 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.AppController: Method Entry: getInstance()
getInstance() finished in 0.000 seconds.
Method Entry: addToRequestQueue()
07-30 22:39:07.409 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.AppController: Method Entry: getRequestQueue()
getRequestQueue() finished in 0.000 seconds.
07-30 22:39:07.410 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.AppController: addToRequestQueue() finished in 0.001 seconds.
07-30 22:39:07.410 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.ContactActivity: onCreate() finished in 0.072 seconds.
07-30 22:39:07.424 24212-31569/com.example.e4977.spotme D/com.example.e4977.spotme.ContactActivity$3: Method Entry: getParams()
07-30 22:39:07.425 24212-31569/com.example.e4977.spotme D/com.example.e4977.spotme.ContactActivity$3: getParams() finished in 0.000 seconds.
07-30 22:39:07.426 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.NewContactActivity$1$1: Method Entry: onResponse()
onResponse() New Contact Response: 
07-30 22:39:07.426 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.NewContactActivity: Method Entry: hideDialog()
07-30 22:39:07.448 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.NewContactActivity: hideDialog() finished in 0.021 seconds.
07-30 22:39:07.448 24212-24212/com.example.e4977.spotme W/System.err: org.json.JSONException: End of input at character 0 of 
    at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
    at org.json.JSONTokener.nextValue(JSONTokener.java:97)
    at org.json.JSONObject.<init>(JSONObject.java:159)
    at org.json.JSONObject.<init>(JSONObject.java:176)
    at com.example.e4977.spotme.NewContactActivity$1$1.onResponse(NewContactActivity.java:119)
07-30 22:39:07.449 24212-24212/com.example.e4977.spotme W/System.err:     at com.example.e4977.spotme.NewContactActivity$1$1.onResponse(NewContactActivity.java:99)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6798)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-30 22:39:07.454 24212-24212/com.example.e4977.spotme D/com.example.e4977.spotme.NewContactActivity$1$1: onResponse() finished in 0.027 seconds.

同样值得注意的是,我看到响应是空的,但我不知道为什么。下面是数据库模式,以防这也是问题的一部分。

DBSchema

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-01 13:00:01

回答

我非常确定这是因为您正在使用mysqli_*函数集,但随后尝试使用mysql_error获取最新的错误文本,它将返回一个空字符串,因为对mysql_*函数的调用没有任何错误。

尝试替换:

代码语言:javascript
复制
$result = mysqli_query($this->conn, /* the rest */) or die (mysql_error());

通过以下方式:

代码语言:javascript
复制
$result = mysqli_query($this->conn, /* the rest */) or die (mysqli_error($this->conn));

您仍然会抛出一个异常,类似于:

代码语言:javascript
复制
org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObject

因为响应将不是有效的JSON,但这应该会对您有所帮助。

旁注

因为这是一个非常典型的问题,所以我不得不在您发布的代码中对SQL注入问题进行评论。有必要通读一下https://cwe.mitre.org/data/definitions/89.html来理解这个问题,然后看看http://php.net/manual/en/mysqli.quickstart.prepared-statements.php,看看如何使用mysqli_preparemysqli_stmt_bind_parammysqli_stmt_execute来组合一个更安全的实现。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51605210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档