Question

I am trying to send user email address and password from my android app to the db to login via POST.

On the server side, I get my data like this :

 $email = $_POST['email'];
 $password = clean($_POST['password'];

And on the android side I send it like so:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("some real URL");
    httppost.setHeader("Content-type", "application/json");

    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));

    httppost.setEntity(new UrlEncodedFormEntity(params));

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httppost);
        ......

Even when I type in valid login details, it fails and says no email address or password. Am I sending things across correctly?

I have also tried sending data across like below but didnt work. Any suggestions?

    JSONObject obj = new JSONObject();
    obj.put("email", email );
    obj.put("password", password);

    httppost.setEntity(new StringEntity(obj.toString()));

No correct solution

OTHER TIPS

HttpPost.setEntity sets the body of the request without any name/value pairings, just raw post data. $_POST doesn't look for raw data, just name value pairs, which it converts into a hashtable/array. You can format the request such that it includes name value pairs.

List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("json", json.toString()));

httppost.setEntity(new UrlEncodedFormEntity(params));

And have the parameters in json object as:

JSONObject json = new JSONObject();
json.put("email", email );
json.put("password", password);

On the server side you can get the data as:

$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);

if( !empty($jsonObj)) { 
    try {
        $email = $jsonObj['email'];
        $password = $jsonObj['password'];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top