我在Android Studio上编写了一个小应用程序,由于我对Google的Firebase非常着迷,因此我尝试使用MySQL进行登录和注册。
我的问题是我仍然遇到完全相同的错误,我不知道问题出在哪里。
错误代码在此类中,并且代码显示“响应错误”:
公共类SetupActivity扩展了AppCompatActivity {
private EditText etusername;
private EditText etemail;
private EditText etpassword;
private EditText etconfirmpw;
private Button btnsetupnext;
private AVLoadingIndicatorView progressBar;
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_EMAIL = "email";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private String username;
private String password;
private String confirmPassword;
private String email;
private ProgressDialog pDialog;
private String register_url = "http://192.168.179.58:81/chatty/register.php";
private SessionHandler session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
etusername = (EditText) findViewById(R.id.accinfousername);
etemail = (EditText) findViewById(R.id.accinfoemail);
etpassword = (EditText) findViewById(R.id.accinfopassword);
etconfirmpw = (EditText) findViewById(R.id.accinfopasswordconfirm);
btnsetupnext = (Button) findViewById(R.id.btnNext);
progressBar = (AVLoadingIndicatorView) findViewById(R.id.accinfoprogress);
btnsetupnext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Retrieve the data entered in the edit texts
username = etusername.getText().toString().toLowerCase().trim();
password = etpassword.getText().toString().trim();
confirmPassword = etconfirmpw.getText().toString().trim();
email = etemail.getText().toString().trim();
if (validateInputs()) {
progressBar.setVisibility(View.VISIBLE);
btnsetupnext.setVisibility(View.GONE);
registerUser();
}
}
});
}
private void displayLoader() {
pDialog = new ProgressDialog(SetupActivity.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Launch Dashboard Activity on Successful Sign Up
*/
private void sendUserToVerification() {
Intent i = new Intent(getApplicationContext(), SetupVerificationActivity.class);
startActivity(i);
finish();
}
private void registerUser() {
displayLoader();
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
request.put(KEY_EMAIL, email);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got registered successfully
if (response.getInt(KEY_STATUS) == 0) {
//Set the user session
session.loginUser(username,email);
sendUserToVerification();
}else if(response.getInt(KEY_STATUS) == 1){
//Display error message if username is already existsing
etusername.setError("Username already taken!");
etusername.requestFocus();
progressBar.setVisibility(View.GONE);
btnsetupnext.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
btnsetupnext.setVisibility(View.VISIBLE);
Toast.makeText(SetupActivity.this, "Error with JSONObject", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
progressBar.setVisibility(View.GONE);
btnsetupnext.setVisibility(View.VISIBLE);
//Display error message whenever an error occurs
Toast.makeText(SetupActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(SetupActivity.this, "Error with Response", Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
/**
* Validates inputs and shows error if any
* @return
*/
private boolean validateInputs() {
if (KEY_EMPTY.equals(username)) {
etusername.setError("Username cannot be empty");
etusername.requestFocus();
return false;
}
if (KEY_EMPTY.equals(email)) {
etemail.setError("Email cannot be empty");
etemail.requestFocus();
return false;
}
if (KEY_EMPTY.equals(password)) {
etpassword.setError("Password cannot be empty");
etpassword.requestFocus();
return false;
}
if (KEY_EMPTY.equals(confirmPassword)) {
etconfirmpw.setError("Confirm Password cannot be empty");
etconfirmpw.requestFocus();
return false;
}
if(!password.equals(confirmPassword)) {
etconfirmpw.setError("Password and Confirm Password doesn't match");
etconfirmpw.requestFocus();
return false;
}
return true;
}
}
以下是重要的PHP脚本:
Register.php:
<?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) &&
isset($input['email'])){
$username = $input['username'];
$password = $input['password'];
$email = $input['email'];
//Check if user already exist
if(!userExists($username)){
//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery = "INSERT INTO member(username, email, password_hash, salt) VALUES (?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$username,$email,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>
然后添加db_conncect.php:
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "chatty"); // database name
define('DB_SERVER', "localhost"); // db server
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
和functions.php:
<?php
$random_salt_length = 32;
function userExists($username){
$query = "SELECT username FROM member WHERE username = ?";
global $con;
if($stmt = $con->prepare($query)){
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
if($stmt->num_rows == 1){
$stmt->close();
return true;
}
$stmt->close();
}
return false;
}
function getSalt(){
global $random_salt_length;
return bin2hex(openssl_random_pseudo_bytes($random_salt_length));
}
function concatPasswordWithSalt($password,$salt){
global $random_salt_length;
if($random_salt_length % 2 == 0){
$mid = $random_salt_length / 2;
}
else{
$mid = ($random_salt_length - 1) / 2;
}
return
substr($salt,0,$mid - 1).$password.substr($salt,$mid,$random_salt_length -
1);
}
?>
MySQL数据库的结构如下:
CREATE TABLE `member` (
`user_id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL unique,
`password_hash` varchar(256) NOT NULL,
`salt` varchar(256) NOT NULL,
`created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;