gpt4 book ai didi

php - Android JSON 与 Volley 和 PHP 输入结束于字符 0

转载 作者:行者123 更新时间:2023-11-29 17:16:10 25 4
gpt4 key购买 nike

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

org.json.JSONException: End of input at character 0 of

我已经四处寻找这个问题,看起来我传递回我的应用程序的 JSON 是空的,所以我知道这个问题,但在我查看的所有地方,解决方案都没有帮助我实际上解决了这个问题,所以我觉得这可能是一个独特的问题。这是我的相关Android代码:

// 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代码:

存储联系人:

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;
}
}

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

<?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 输出:

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

最佳答案

回答

我相当确定出现这种情况的原因是您正在使用 mysqli_* 函数集,但随后尝试使用 mysql_error 获取最新的错误文本,这将返回一个空字符串,因为调用 mysql_* 函数没有错误。

尝试替换:

$result = mysqli_query($this->conn, /* the rest */) or die (mysql_error());

与:

$result = mysqli_query($this->conn, /* the rest */) or die (mysqli_error($this->conn));

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

org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObject

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

旁注

因为这是一个非常经典的问题,所以我无法避免在您发布的代码中评论 SQL 注入(inject)问题。值得一读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 组合出更安全的实现。

关于php - Android JSON 与 Volley 和 PHP 输入结束于字符 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com