如何安全地连接android到mysql数据库

时间:2016-03-27 15:34:13

标签: android mysql database security

我有一个与梦想主机的phpmyadmin设置。让我们说比如说我想从android中检索数据库中的用户名和密码,我该怎么做呢?要访问我的数据库,我需要数据库的用户名和密码,那么如何在没有人能够查看我的应用程序的源代码并查看数据库凭据的情况下通过android连接?

编辑:我有一个很大的误解,我在哪里存储php webservice文件?不在设备上,对吧?

2 个答案:

答案 0 :(得分:3)

您可以直接连接到MySQL,但不是一个好的做法,特别是对于生产应用程序。我的建议是使用一个便于连接的Web服务。

Web服务是指企业Web服务器为Web用户或其他Web连接程序(在本例中为您的Android应用程序)提供的服务。

这是一个很棒的教程,可以帮助您入门Android, MySQL and PHP

答案 1 :(得分:-1)

创建一个类来向服务器发出HTTP请求。例如(我使用JSON解析来获取值):

public class JSONfunctions {
      public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {
            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
      }
    }

在MainActivity中,使用类JsonFunctions创建一个对象,并从您希望获取数据的URL作为参数传递。例如:

JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");

然后最后读取JSON标记并将值存储在ArrayList中。稍后,如果需要,可以在ListView中显示它们。

您可以在Can an Android App connect directly to an online mysql database

找到答案