How to connect android to mysql database securely

2019-08-09 10:32发布

问题:

I have a phpmyadmin setup with dream host. Lets say for instance I wanted to retrieve user names and passwords from the database from android, how would I go about doing that? To access my database, I need the username and password for the database, so how can I connect through android without people being able to view the source code of my app and see the database credentials?

EDIT: A big misunderstanding I have is, where do I store the php webservice file? Not on the device, right?

回答1:

You can connect directly to MySQL, but is not a good practice, specially for production apps. My advice is to use a Web service that will facilitate the connection.

Web services are services that are made available from a business's Web server for Web users or other Web-connected programs, in this case, your Android app.

Here is a great tutorial to get you started Android, MySQL and PHP



回答2:

Make a class to make an HTTP request to the server. For example (I am using JSON parsing to get the values):

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;
      }
    }

In your MainActivity, make an object with the class JsonFunctions and pass the URL from where you want to get the data as an argument. For example:

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

And then finally read the JSON tags and store the values in an ArrayList. Later, show them in a ListView if you want.

You might find an answer here Can an Android App connect directly to an online mysql database