我已经从我发现的模型中使用php构建了一个REST服务,但在尝试和尝试之后我无法获得任何结果。
应用程序构建没有错误。但是,当我尝试在我的设备中测试时,它不起作用 我找不到任何错误。
这是我写的代码,如果有人能帮助我,我将不胜感激。
翻译注意:
Correo =电子邮件
Contrasena =密码
Nombre =姓名
Encriptada =加密的将Salt名称更改为claveApi
logcat的
02-16 13:01:56.107 27336-27336/com.amg_eservices.mywisen D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
02-16 13:01:56.308 27336-29449/com.amg_eservices.mywisen I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
02-16 13:01:56.318 27336-29449/com.amg_eservices.mywisen I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
02-16 13:01:56.548 27336-29449/com.amg_eservices.mywisen I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: org.json.JSONException: Value <html><head> of type java.lang.String cannot be converted to JSONObject
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.amg_eservices.mywisen.RegisterandLogin.RegistrationActivity$3.onResponse(RegistrationActivity.java:103)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.amg_eservices.mywisen.RegisterandLogin.RegistrationActivity$3.onResponse(RegistrationActivity.java:96)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at android.os.Looper.loop(Looper.java:145)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5951)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
02-16 13:01:56.708 27336-27336/com.amg_eservices.mywisen E/ViewRootImpl: sendUserActionEvent() mView == null
02-16 13:02:26.137 27336-27336/com.amg_eservices.mywisen V/ActivityThread: updateVisibility : ActivityRecord{2f1aeb60 token=android.os.BinderProxy@3b2fb0be {com.amg_eservices.mywisen/com.amg_eservices.mywisen.RegisterandLogin.RegistrationActivity}} show : true
02-16 13:02:27.178 27336-27336/com.amg_eservices.mywisen W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection`
MySQL数据库
使用“usuarios”表
idUsuario | nombre | contrasena | claveApi | correo
结构:
PHP
公共访问root到php rest
我在hostinger中有一个名为v1.2
的子目录内
DB_Function.php
db_Connect.php
db_config.php
的index.php
在APP中
AppController的
AppURLs
LoginActivity
MainActivity
RegistrationActivity
会话
SplashScreenActivity
AppController的
package com.amg_eservices.mywisen.RegisterandLogin;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
*/
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private static AppController mInstance;
private RequestQueue mRequestQueue;
public static synchronized AppController getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
AppURLs
package com.amg_eservices.mywisen.RegisterandLogin;
public class AppURLs {
public static String URL = "http://wi-sen.esy.es/v1.2";
}
LoginActivity
package com.amg_eservices.mywisen.RegisterandLogin;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
private Button registrationButton, loginButton;
private EditText email_to_login, password_to_login;
private ProgressDialog progressDialog;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
session = new Session(LoginActivity.this);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
registrationButton = (Button) findViewById(R.id.registration_button);
loginButton = (Button) findViewById(R.id.signin_button);
email_to_login = (EditText) findViewById(R.id.email_to_login);
password_to_login = (EditText) findViewById(R.id.password_to_login);
registrationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
RegistrationActivity.class);
startActivity(intent);
finish();
}
});
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String email = email_to_login.getText().toString();
String password = password_to_login.getText().toString();
if (email.trim().length() > 0 && password.trim().length() > 0) {
checkLogin(email, password);
} else {
Snackbar.make(v, "Please enter the credentials!", Snackbar.LENGTH_LONG)
.show();
}
}
});
}
private void checkLogin(final String email, final String password) {
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppURLs.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
String userId = jObj.getString("user_id");
if (userId != null) {
session.setLogin(true);
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Post params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}`
MainActivity
package com.amg_eservices.mywisen.RegisterandLogin;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btnLogout;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
btnLogout = (Button) findViewById(R.id.btnLogout);
session = new Session(MainActivity.this);
if (!session.getLoggedIn()) {
logoutUser();
}
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logoutUser();
}
});
}
private void logoutUser() {
session.setLogin(false);
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
RegistrationActivity
package com.amg_eservices.mywisen.RegisterandLogin;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class RegistrationActivity extends AppCompatActivity {
private TextView tvLogin;
private EditText fullName, email_to_register, password_to_register;
private Button registerButton;
private Session session;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
session = new Session(RegistrationActivity.this);
if (session.getLoggedIn()) {
Intent intent = new Intent(RegistrationActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
registerButton = (Button) findViewById(R.id.register_button);
fullName = (EditText) findViewById(R.id.fullname_register);
email_to_register = (EditText) findViewById(R.id.email_register);
password_to_register = (EditText) findViewById(R.id.password_register);
tvLogin = (TextView) findViewById(R.id.tv_signin);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nombre = fullName.getText().toString();
String correo = email_to_register.getText().toString();
String contrasena = password_to_register.getText().toString();
if (!nombre.isEmpty() && !correo.isEmpty() && !contrasena.isEmpty()) {
registerUser(nombre, correo, contrasena);
} else {
Snackbar.make(v, "Porfavor introduzca las credenciales!", Snackbar.LENGTH_LONG)
.show();
}
}
});
tvLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegistrationActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
}
});
}
private void registerUser(final String nombre, final String correo,
final String contrasena) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registrando ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppURLs.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Intent intent = new Intent(
RegistrationActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "registro");
params.put("nombre", nombre);
params.put("correo", correo);
params.put("contrasena", contrasena);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
会话
package com.amg_eservices.mywisen.RegisterandLogin;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Session {
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;
public Session(Context context) {
sp = PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean setLogin(boolean status) {
spEditor = sp.edit();
spEditor.putBoolean("is_logged_in", status);
spEditor.commit();
return true;
}
public boolean getLoggedIn() {
return sp.getBoolean("is_logged_in", false);
}
}
SplashScreenActivity
这只是登录屏幕的简单跳转屏幕。 &gt;不重要
的index.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
/**
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include DB_function
require_once 'DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "error" => FALSE);
// checking tag
if ($tag == 'login') {
// Request type is check Login
$correo = $_POST['correo'];
$contrasena = $_POST['contrasena'];
// check for user
$user = $db->getUserByEmailAndPassword($correo, $contrasena);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["idUsuario"] = $user["idUsuario"];
$response["user"]["nombre"] = $user["nombre"];
$response["user"]["correo"] = $user["correo"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "correo incorrecto o contraseña incorrecta!";
echo json_encode($response);
}
} else if ($tag == 'registro') {
// Request type is Register new user
$nombre = $_POST['nombre'];
$correo = $_POST['correo'];
$contrasena = $_POST['contrasena'];
// check if user is already existed
if ($db->isUserExisted($correo)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "Usuario ya existente";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($nombre, $correo, $contrasena);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["idUsuario"];
$response["user"]["nombre"] = $user["nombre"];
$response["user"]["correo"] = $user["correo"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Ha ocurrido un error en el registro";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Etiqueta desconocida, debe seleccionar o login o registro";
echo json_encode($response);
}
} else {
?><html><head>
<title>Inicializando Android | API</title>
</head>
<body style="background:#2c3e50;">
<div style="margin:0 auto; margin-top:200px;width:60%;">
<img src="logo_api.png" alt="Iniciando Android">
</div>
</body></html><?php
}
?>
DB_Function.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Store user details
*/
public function storeUser($nombre, $correo, $contrasena) {
$hash = $this->hashSSHA($contrasena);
$contrasena = $hash["encriptada"]; // encrypted password
$claveApi = $hash["claveApi"]; // salt
$resultado = mysqli_query($this->db->con,"INSERT INTO usuarios(nombre, correo, contrasena, claveApi) VALUES('$nombre', '$correo', '$contrasena', '$claveApi')") or die(mysqli_error($this->db));
// check for result
if ($resultado) {
// gettig the details
$uid = mysqli_insert_id($this->db->con); // last inserted id
$resultado = mysqli_query($this->db->con,"SELECT * FROM usuarios WHERE idUsuario = $uid");
// return details
return mysqli_fetch_array($resultado);
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($correo, $contrasena) {
$resultado = mysqli_query($this->db->con,"SELECT * FROM usuarios WHERE correo = '$correo'") or die(mysqli_connect_error());
// check for result
$no_of_rows = mysqli_num_rows($resultado);
if ($no_of_rows > 0) {
$resultado = mysqli_fetch_array($resultado);
$claveApi = $resultado['claveApi'];
$contrasena = $resultado['contrasena'];
$hash = $this->checkhashSSHA($claveApi, $contrasena);
// check for password
if ($contrasena == $hash) {
return $resultado;
}
} else {
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($correo) {
$resultado = mysqli_query($this->db->con,"SELECT correo from usuarios WHERE correo = '$correo'");
$no_of_rows = mysqli_num_rows($resultado);
if ($no_of_rows > 0) {
// user exist
return true;
} else {
// user not exist
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($contrasena) {
$claveApi = sha1(rand());
$claveApi = substr($claveApi, 0, 10);
$encriptada = base64_encode(sha1($contrasena . $claveApi, true) . $claveApi);
$hash = array("claveApi" => $claveApi, "encriptada" => $encriptada);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($claveApi, $contrasena) {
$hash = base64_encode(sha1($contrasena . $claveApi, true) . $claveApi);
return $hash;
}
}
?>`
答案 0 :(得分:0)
您的错误:
org.json.JSONException: Value <html><head> of type java.lang.String cannot be converted to JSONObject
表示您打开了错误的网址或index.php的else
部分。当您希望收到JSON内容时,您的服务器会返回一个标准的html网页。