【问题标题】:Android remote database connection using PHP and JSON使用 PHP 和 JSON 的 Android 远程数据库连接
【发布时间】:2015-05-13 19:54:31
【问题描述】:

我正在尝试学习 android 中的远程数据库连接。我在互联网上找到了一个使用 PHP 和 JSON 的教程。它工作正常。但是 PHP 脚本会在同一网页中回显已编码的 JSON 数据。只有这样,数据才会传递给 android 应用程序。仅将 PHP 脚本用于移动应用程序时可能没问题。

但是,如果我还希望将我的想法作为网站发布呢?我不希望 json 数据在网页上可见。我遇到的所有 php 脚本似乎都以相同的方式对 JSON 数据进行编码。

是否可以将 JSON 数据传递给 android 应用程序而不在网页上回显?还是我必须为网站和移动应用程序创建单独的 PHP 脚本?我已经在下面添加了到目前为止我工作过的代码。

登录.php:

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
//gets user's info based off of a username.
$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    // For testing, you could use a die and message. 
    //die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one to product JSON data:
    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}

//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$login_ok = false;

//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
    //if we encrypted the password, we would unencrypt it here, but in our case we just
    //compare the two passwords
    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}

// If the user logged in successfully, then we send them to the private members-only page 
// Otherwise, we display a login failed message and show the login form again 
if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));

} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
}
} else {
?>
    <h1>Login</h1> 
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value="" /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php
}

?> 

Android java 文件-Login.java

package com.example.mysqltest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;

 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1




private static final String LOGIN_URL =     "http://192.168.1.2:8080/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    //setup input fields
    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);

    //setup buttons
    mSubmit = (Button)findViewById(R.id.login);
    mRegister = (Button)findViewById(R.id.register);

    //register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.login:
            new AttemptLogin().execute();
        break;
    case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
        break;

    default:
        break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());

                SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(Login.this);
                Editor edit=sp.edit();
                edit.putString("username", username);
                edit.commit();

                Intent i = new Intent(Login.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}

【问题讨论】:

    标签: php android mysql json remote-access


    【解决方案1】:

    是否可以将json数据传递给android应用程序而不在网页上回显?

    不,因为这是 Web 服务器与客户端通信的方式。但是,您可以为网站和移动应用程序的 api 使用大部分相同的代码。只需将您的逻辑与您的演示文稿分开即可。在一个地方进行处理,在另一个地方进行演示。也许研究一个可以帮助你做到这一点的框架,比如Laravel。您可以在模型中进行处理,并为您的 api 和您的网站设置单独的控制器。

    【讨论】:

      【解决方案2】:

      我会这样写,

      1. 有一个 php 脚本,它接受用户名/密码并返回 JSON 输出,成功或失败。
      2. 我将从 android 应用程序调用该 php 脚本。
      3. 对于网页,我将编写一个带有用户名/密码表单字段的简单 html 页面,并使用 AJAX 调用 php 脚本。

      您的 php 脚本试图成为一个网页和一个服务,所以我认为这需要解耦。

      将您的 php 视为 Android 和 HTML 网页的服务提供商。

      【讨论】:

      • 但即使我这样做了,它也会再次执行相同的过程,不是吗?它会回显编码的 JSON 数据,不是吗?
      • 因此,如果您的目标是隐藏“由 php 脚本生成的 JSON 响应”,那么这是不可能的。 HTTP 适用于请求响应协议,响应数据对用户可见。最多可以使用 https 协议,这样就没有人可以欺骗数据。尽管如此,如果有人将您的 php 脚本放在浏览器中,他们将能够看到响应数据。
      • 我正在考虑的一个解决方案是从您的应用程序发送自定义标头/cookie 数据。在 php 脚本上,如果您看到自定义标头,请使用 JSON 响应。如果 header 不存在,则发送一些垃圾数据或重定向到其他一些 url。虽然,我不确定,但可能在 http 服务器中,您可能可以设置一个规则来仅处理那些包含某些标头的 http 请求。
      猜你喜欢
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2021-02-25
      • 2017-06-22
      • 2016-09-28
      相关资源
      最近更新 更多