使用Slim Rest服务器和android客户端进行用户注册
我正在开发一个简单的应用程序,注册新用户。 -我在apache本地主机上使用带MySQL的SLIM PHP框架 -我有一个MySQL数据库,表名为tbl_user。我已经使用CURL测试了我的SLIM实现 -在客户端,我有三个名为fname、email和password的EditView字段,还有一个注册按钮 -它很简单,当用户单击“注册”按钮时,应该建立数据库连接,并在数据库中添加新用户。注册很简单,不需要任何支票。一旦我解决了这个问题,我将实施 请帮忙。我已经搜索了很多,无法解决错误 我遇到以下错误: 错误 这是我现在的实际错误使用Slim Rest服务器和android客户端进行用户注册,android,http,android-asynctask,slim,jsonexception,Android,Http,Android Asynctask,Slim,Jsonexception,我正在开发一个简单的应用程序,注册新用户。 -我在apache本地主机上使用带MySQL的SLIM PHP框架 -我有一个MySQL数据库,表名为tbl_user。我已经使用CURL测试了我的SLIM实现 -在客户端,我有三个名为fname、email和password的EditView字段,还有一个注册按钮 -它很简单,当用户单击“注册”按钮时,应该建立数据库连接,并在数据库中添加新用户。注册很简单,不需要任何支票。一旦我解决了这个问题,我将实施 请帮忙。我已经搜索了很多,无法解决错误 我遇到
01-27 08:42:14.981:D/URL读取(6739):Slim应用程序错误体{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans serif;}h1{margin:0;字体大小:48px;字体重量:正常;行高:48px;}strong{显示:内联块;宽度:65px;}Slim应用程序错误由于以下错误,应用程序无法运行:详细信息:消息:错误日志(/var/tmp/php.log)[function.Error log]:无法打开流:没有这样的文件或目录
文件:C:\xampp\htdocs\api\index.php
行:105
堆栈跟踪:\0[内部函数]:Slim::handleErrors(2,'错误日志(/var/…,'C:\xampp\htdocs…',105,数组)
01-27 08:42:14.981:D/URL读取(6739):#1c:\xampp\htdocs\api\index.php(105):错误日志('SQLSTATE[23000]…',3',/var/tmp/php.lo…')
01-27 08:42:14.981:D/URL读取(6739):#2[内部函数]:register()
01-27 08:42:14.981:D/URL读取(6739):#3 C:\xampp\htdocs\api\Slim\Route.php(392):调用用户函数数组(“寄存器”,数组)
01-27 08:42:14.981:D/URL读取(6739):#4c:\xampp\htdocs\api\Slim\Slim.php(1052):Slim_-Route->dispatch()
01-27 08:42:14.981:D/URL读取(6739):#5c:\xampp\htdocs\api\index.php(26):Slim->run()
01-27 08:42:14.981:D/URL读取(6739):#6{main} RegisterActivity.java(部分)
类CreateNewUser扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(RegisterActivity.this);
pDialog.setMessage(“注册…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创建用户
* */
受保护的字符串doInBackground(字符串…args){
字符串fname=mUsername.getText().toString();
字符串email=mEmail.getText().toString();
字符串密码=mPassword.getText().toString();
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
添加(新的BasicNameValuePair(“密码”,password));
添加参数(新的BasicNameValuePair(“fname”,fname));
//获取JSON对象
//请注意,创建用户url接受POST方法
JSONObject json=jsonParser.makeHttpRequest(url\u create\u product,
“POST”,params);
//从响应中检查日志cat
//d(“创建响应”,json.toString());
//检查成功标签
试一试{
int success=json.getInt(TAG_success);
如果(成功==1){
//已成功创建用户
Intent i=newintent(getApplicationContext(),UserHome.class);
星触觉(i);
//关闭此屏幕
//完成();
}否则{
//无法创建用户
//Log.d(“无注册”,json.toString());
}
}捕获(JSONException e){
//Log.e(“Log_标记”,“错误解析数据”+e.toString());
//Log.e(“日志标记”,“失败的数据是:\n”+标记成功);
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//完成后关闭对话框
pDialog.disclose();
}
}
java(部分)
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Signing Up..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating User
* */
protected String doInBackground(String... args) {
String fname = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("fname", fname));
// getting JSON Object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat from response
//Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created USER
Intent i = new Intent(getApplicationContext(), UserHome.class);
startActivity(i);
// closing this screen
// finish();
} else {
// failed to create USER
// Log.d("No Sign Up.", json.toString());
}
} catch(JSONException e){
// Log.e("log_tag", "Error parsing data "+e.toString());
// Log.e("log_tag", "Failed data was:\n" + TAG_SUCCESS);
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
<?php
session_start();
require 'Slim/Slim.php';
$app = new Slim();
$app->post('/login', 'login');
$app->post('/register', 'register');
$app->response()->header('Content-Type', 'application/json');
$app->get('/users', 'getUsers');
$app->get('/users/:id', 'getUser');
$app->get('/users/search/:query', 'findByName');
$app->post('/users', 'addUser');
$app->put('/users/:id', 'updateUser');
$app->delete('/users/:id', 'deleteUser');
$app->get('/gametype', 'getgameType');
$app->run();
// AUTHENTICATION START
function login() {
$request = Slim::getInstance()->request();
$user = json_decode($request->getBody());
$email= $user->email;
$password= $user->password;
// echo $email;
// echo $password;
if(!empty($email)&&!empty($password))
{
$sql="SELECT email, fname, role FROM tbl_user WHERE email='$email' and password='$password'";
$db = getConnection();
try {
$result=$db->query($sql);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
$row["user"]= $result->fetchAll(PDO::FETCH_OBJ);
$db=null;
echo json_encode($row);
} catch(PDOException $e) {
error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
// AUTHENTICATION END
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
// Register START
function register() {
$request = Slim::getInstance()->request();
$user = json_decode($request->getBody());
$sql = "INSERT INTO tbl_user (email, password, fname) VALUES (:email, :password, :fname)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("fname", $user->fname);
$stmt->bindParam("password", $user->password);
$stmt->bindParam("email", $user->email);
$stmt->execute();
$user->id = $db->lastInsertId();
$db = null;
print('{"success":1}');
} catch(PDOException $e) {
error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
// Register END
function register()
{
$request = Slim::getInstance()->request();
$response = Slim::getInstance()->response();
$response['Content-Type'] = 'application/json; charset=utf-8';
/* rest of your function here*/
}