- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
PHP 文件:
<?php
require_once('include/db_functions.php');
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters username or password is missing!";
}
echo json_encode($response);
?>
Java代码:
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
int jsonStart = response.indexOf('{');
int jsonEnd = response.lastIndexOf('}');
if(jsonStart>=0 && jsonEnd>=0 && jsonEnd>jsonStart) response = response.substring(jsonStart,jsonEnd+1);
else response = "";
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
UPDATE 1: Logcat:
03-01 15:13:12.889 2099-2099/challenge.edison.harvest I/art: Not late-
enabling -Xcheck:jni (already on)
03-01 15:13:13.021 2099-2099/challenge.edison.harvest W/System: ClassLoader referenced unknown path: /data/app/challenge.edison.harvest-1/lib/x86
03-01 15:13:13.143 2099-2113/challenge.edison.harvest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-01 15:13:13.256 2099-2113/challenge.edison.harvest I/OpenGLRenderer: Initialized EGL, version 1.4
03-01 15:13:13.386 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:13.386 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7345a0, error=EGL_SUCCESS
03-01 15:13:30.769 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:30.769 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad73a840, error=EGL_SUCCESS
03-01 15:13:33.005 2099-2105/challenge.edison.harvest W/art: Suspending all threads took: 779.254ms
03-01 15:13:33.006 2099-2099/challenge.edison.harvest I/Choreographer: Skipped 48 frames! The application may be doing too much work on its main thread.
03-01 15:13:34.301 2099-2105/challenge.edison.harvest W/art: Suspending all threads took: 629.777ms
03-01 15:13:34.302 2099-2099/challenge.edison.harvest I/Choreographer: Skipped 38 frames! The application may be doing too much work on its main thread.
03-01 15:13:35.046 2099-2099/challenge.edison.harvest D/RegisterActivity: Login Response: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'><b>PHP Error Message</b></font></td></tr></table><br />
<b>Fatal error</b>: Call to undefined method mysqli_stmt::get_result() in <b>/home/a6777446/public_html/include/db_functions.php</b> on line <b>64</b><br />
<br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'><a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr></table>
03-01 15:13:35.089 2099-2113/challenge.edison.harvest E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7510d0
03-01 15:13:35.096 2099-2099/challenge.edison.harvest W/System.err: org.json.JSONException: End of input at character 0 of
03-01 15:13:35.096 2099-2099/challenge.edison.harvest W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err: at org.json.JSONObject.<init>(JSONObject.java:156)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
03-01 15:13:35.097 2099-2099/challenge.edison.harvest W/System.err: at challenge.edison.harvest.LoginActivity$3.onResponse(LoginActivity.java:128)
03-01 15:13:35.100 2099-2099/challenge.edison.harvest W/System.err: at challenge.edison.harvest.LoginActivity$3.onResponse(LoginActivity.java:115)
03-01 15:13:35.102 2099-2099/challenge.edison.harvest W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-01 15:13:35.103 2099-2099/challenge.edison.harvest W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at android.os.Looper.loop(Looper.java:148)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-01 15:13:35.104 2099-2099/challenge.edison.harvest W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-01 15:13:35.113 2099-2099/challenge.edison.harvest D/Volley: [1] Request.finish: 4449 ms: [ ] http://edisonharvest.comxa.com/login.php 0xafab10d0 NORMAL 1
03-01 15:13:35.242 2099-2113/challenge.edison.harvest W/EGL_emulation: eglSurfaceAttrib not implemented
03-01 15:13:35.242 2099-2113/challenge.edison.harvest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad75aae0, error=EGL_SUCCESS
03-01 15:13:38.626 2099-2113/challenge.edison.harvest E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7524f0
UPDATE 2: DB_FUNCTIONS.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
注册时数据存储在服务器上,但我在登录时收到此错误。好像我得到的是空的 json 对象。我正在使用 000webhost。我正在为一个重要的项目工作。请帮忙!!!谢谢!!
最佳答案
像下面这样更改函数 getUserByEmailAndPassword
。
将查询更改为以下内容或按原样进行并更改 $stmt->bind_result()
$stmt->bind_result($col1, $col2, $col3)
根据 SELECT *
查询检索到的列的方法。
$stmt = $this->conn->prepare("SELECT salt, encrypted_password FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$stmt->bind_result($salt, $encrypted_password);
if($stmt->fetch()) {
// verifying user password
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
$user = array();
$user["salt"] = $salt;
$user["encrypted_password"] = $encrypted_password;
// if you want to return all the columns from database
// then add other lines here
// like $user["name"] = $name;
// and make sure you have declared $name in bind_result method
return $user;
}
} else {
return NULL;
}
} else {
return NULL;
}
也不要忘记对所有其他功能进行相对更改。
有关更多详细信息,请查看此 guid mysqli
希望对你有帮助。
关于java - 获取 json 错误 : end of input at character 0 of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35718426/
最近开始学习MongoDB。今天老师教了我们 mongoexport 命令。在练习时,我遇到了一个典型的问题,包括教练在内的其他同学都没有遇到过。我在我的 Windows 10 机器上使用 Mongo
我是 JSON Schema 的新手,读过什么是 JSON Schema 等等。但我不知道如何将 JSON Schema 链接到 JSON 以针对该 JSON Schema 进行验证。谁能解释一下?
在 xml 中,我可以在另一个 xml 文件中包含一个文件并使用它。如果您的软件从 xml 获取配置文件但没有任何方法来分离配置,如 apache/ngnix(nginx.conf - site-av
我有一个 JSON 对象,其中包含一个本身是 JSON 对象的字符串。我如何反序列化它? 我希望能够做类似的事情: #[derive(Deserialize)] struct B { c: S
考虑以下 JSON { "a": "{\"b\": 12, \"c\": \"test\"}" } 我想定义一个泛型读取 Reads[Outer[T]]对于这种序列化的 Json import
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 11 个月前关闭。 Improve
我的旧项目在 MySQL 中有 Standard JSON 格式的数据。 对于我在 JS (Node.js) 和 DynamoDB 中的全新项目,关于 Standard JSON格式: 是否建议将其转
JSON 值字符串、数字、true、false、null 是否是有效的 JSON? 即,是 true 一个有效的 JSON 文档?还是必须是数组/对象? 一些验证器接受这个(例如 http://jso
我有一个 JSON 字符串,其中一个字段是文本字段。这个文本字段可以包含用户在 UI 中输入的文本,如果他们输入的文本是 JSON 文本,也许是为了说明一些编码,我需要对他们的文本进行编码,以便它不会
我正在通过 IBM MQ 调用处理数据,当由 ColdFusion 10 (10,0,11,285437) 序列化时,0 将作为 +0.0 返回,它会导致无效的 JSON并且无法反序列化。 stPol
我正在从三个数组中生成一个散列,然后尝试构建一个 json。我通过 json object has array 成功了。 require 'json' A = [['A1', 'A2', 'A3'],
我从 API 接收 JSON,响应可以是 30 种类型之一。每种类型都有一组唯一的字段,但所有响应都有一个字段 type 说明它是哪种类型。 我的方法是使用serde .我为每种响应类型创建一个结构并
我正在下载一个 JSON 文件,我已将其检查为带有“https://jsonlint.com”的有效 JSON 到文档目录。然后我打开文件并再次检查,结果显示为无效的 JSON。这怎么可能????这是
我正在尝试根据从 API 接收到的数据动态创建一个 JSON 对象。 收到的示例数据:将数据解码到下面给出的 CiItems 结构中 { "class_name": "test", "
我想从字符串转换为对象。 来自 {"key1": "{\n \"key2\": \"value2\",\n \"key3\": {\n \"key4\": \"value4\"\n }\n
目前我正在使用以下代码将嵌套的 json 转换为扁平化的 json: import ( "fmt" "github.com/nytlabs/gojsonexplode" ) func
我有一个使用来自第三方 API 的数据的应用程序。我需要将 json 解码为一个结构,这需要该结构具有“传入”json 字段的 json 标签。传出的 json 字段具有不同的命名约定,因此我需要不同
我想使用 JSON 架构来验证某些值。我有两个对象,称它们为 trackedItems 和 trackedItemGroups。 trackedItemGroups 是组名称和 trackedItem
考虑以下案例类模式, case class Y (a: String, b: String) case class X (dummy: String, b: Y) 字段b是可选的,我的一些数据集没有字
我正在存储 cat ~/path/to/file/blah | 的输出jq tojson 在一个变量中,稍后在带有 JSON 内容的 curl POST 中使用。它运作良好,但它删除了所有换行符。我知
我是一名优秀的程序员,十分优秀!