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/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie