0

I have tried looking at several links but I cannot seem to get it right. I am trying to send a JSON object from my android application which contains 'username' and 'password'. But I am not sure if this data is actually been sent to the web-service. I am not too sure if I got the code right for reading JSON object in the php script.

    JSONObject jsonObject = new JSONObject();

    String userID = "";

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(loginURI);
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
    HttpConnectionParams.setSoTimeout(httpParams,10000);

    try {

        jsonObject.put("username", username);
        jsonObject.put("password", password);

        JSONArray array = new JSONArray();

        StringEntity stringEntity = new StringEntity(jsonObject.toString());
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            userID = EntityUtils.toString(httpResponse.getEntity());
            Log.i("Read from server", userID);
         }

    }catch (IOException e){
        Log.e("Login_Issue", e.toString());
    }catch (JSONException e) {
        e.printStackTrace(); 
    }

Here is the beginning of the PHP script.

<?php

include('dbconnect.php'); 

$tablename = 'users';

 //username and password sent from android
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];

 .....
 ?>

Can you tell me what I'm doing wrong here please? I cannot seem to figure out.

Thank you

1 Answer 1

1

You should add a list of NameValuePairs to your HttpPost object, so you know the keys you can use to retrieve the data in your PHP script. See the example code snippets below.

The Java:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

The PHP:

$username = $_POST['username']
$password = $_POST['password']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It did the trick. Could you tell me the difference between $_REQUEST and $_POST please? Thank you
$_REQUEST is for all type of methods including get and post. $_POST is for only post methods

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.