0

I'm a novice creating a basic login app for Android, using 000webhost as my server.

My Java code:

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("name", user.name));
        dataToSend.add(new BasicNameValuePair("email", user.email));
        dataToSend.add(new BasicNameValuePair("password", user.password));
        dataToSend.add(new BasicNameValuePair("leagueID", user.leagueID + ""));

        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost("http://subdomain.site88.net/register.php");

        try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            client.execute(post);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;

My PHP code

<?php
$con = mysqli_connect("mysql1.000webhost.com", "username", "password", "dbname");

/***I want to get this data from Java side of application***/
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$leagueID = $_POST["LeagueID"];

/***this works
$name = "John Doe";
$email = "[email protected]";
$password = "password"
$leagueID = 0;
***/

echo "Hello";//place this here to check website to see if its showing up

//Now we will add the name, email, password, and leagueID into a table called "user".
$statement = mysqli_prepare($con, "INSERT INTO user (email, name, password, leagueID) VALUES (?, ?, ?, ?)"); 
mysqli_stmt_bind_param($statement, "sssi", $email, $name, $password, $leagueID);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
//finish up by closing the connection
mysqli_close($con);
?>

If I hardwire the values into the PHP code instead of using the $_POST method, it is sent to the database as requested. However, it seems that the $_POST variable is empty. I'm not quite sure why this is the case. Is it perhaps that 000webhost has some sort of setting that doesn't allow for someone to post data?

Also, I'm aware that I'm using deprecated java methods and how insecure my password storage currently is. I'll modify that in the future, but I'd first like to know how to post data.

Thanks in advance!

1 Answer 1

1

HttpClient is now deprecated, so you should use HttpUrlConnection instead, to send post request to server.

Create a new Class which will send a asynchronous post request to your server.

public class YourAyncClass extends AsyncTask<String, Void, String>{


    public YourAyncClass(Context c){

        this.context = c;
    }

    public SaveCampaign(){}

    protected void onPreExecute(){}

    @Override
    protected String doInBackground(String... arg0) {

        try{
            URL url = new URL("Your url here");             

            JSONObject urlParameters = new JSONObject();
            urlParameters.put("name", "John Doe");
            urlParameters.put("email", "[email protected]");
            urlParameters.put("password", "xxxxxx");
            urlParameters.put("leagueId", "123-456");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);

            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(urlParameters));
            writer.flush();
            writer.close();
            os.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                StringBuffer sb = new StringBuffer("");
                String line = "";

                while ((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();
            }
            else {
                return new String("New Exception : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

    protected void onPostExecute(String result){

    }   


    /*This method changes the json object into url encoded key-value pair*/
    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}

Now, to use this class in your method you need to implement following code in your code :

new YourAsyncClass(context).execute();

The above line of code calls the execute() method of AsyncTask class and starts the execution of your http call to server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.