1

Android/PHP: how to POST/GET JSON data from Android to php?

Currently I am stuck at a point where I am sending JSONObject data to php but getting NULL values always in response.

What I want:

I am sending 'username' and 'password' from Android in the form of JSONObject and want to retrieve same data in JSONObject in PHP response.

Here is my code snippet

Android_file.java

DefaultHttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(register_user);
        JSONObject jsonObject=new JSONObject();
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        try {

            jsonObject.put("username",username.getText().toString());
            jsonObject.put("password",password.getText().toString());
            StringEntity se=new StringEntity("json="+jsonObject.toString());
            //httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            httpPost.setEntity(se);
           String req=se.toString();

            HttpResponse response=httpClient.execute(httpPost);


            if(response!=null){
                InputStream is=response.getEntity().getContent();
                BufferedReader bufferedReader=new BufferedReader(new     InputStreamReader(is));
                StringBuilder sb=new StringBuilder();
                String line=null;
                while((line=bufferedReader.readLine())!=null){
                    sb.append(line+"\n");
                }
                this.message=sb.toString();
                //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Login_check.php

<?php
include('../core/init.php');

 // $contents = file_get_contents('php://input'); 
  // $contents = utf8_encode($contents); 
  if($_POST['json'])
  {
  $data=json_decode(stripslashes($_POST['json']));
  $username=$data['username'];
  $password=$data['password'];
$response=array('username'=>$username,'password'=>$password);
echo json_encode($response);

  }
   else{
   $no_data=array('none'=>'no data received');
echo json_encode($no_data);
   }

    ?>

Please let me know if I am doing something wrong or missing some point? thanks in advance!

7
  • 1
    Please search StackOverflow before posting, it seems like this question is asked almost daily... Commented May 15, 2015 at 13:40
  • @Ed George- I've seen lot of answers but none of them have clear-satisfied answer what i wanted . Commented May 15, 2015 at 13:42
  • Please let me know i am doing something wrong or missing some point? ... You missed to use internet searching engine ... prolly yet another NOMTException ... Commented May 15, 2015 at 13:44
  • @Selvin: I've spent almost a day to get answer for this question on INTERNET on google/stackoverflow. No offence but if any of you can help/assist me then it'd be great help from you guys. I am a beginner to this concept. Commented May 15, 2015 at 13:48
  • off-topic: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. in other words bit.ly/Vn6wfB Commented May 15, 2015 at 13:49

1 Answer 1

1

I dont know what exactly is wrong with your code but I compared your code to mine which is working fine on diffrent apps and I made some changes to your code and hope that it works:

replace the part:

        jsonObject.put("username",username.getText().toString());
        jsonObject.put("password",password.getText().toString());
        StringEntity se=new StringEntity("json="+jsonObject.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        httpPost.setEntity(se);

With:

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

and this will be your web service (I think the problem is here):

<?php
include('../core/init.php');

 // $contents = file_get_contents('php://input'); 
  // $contents = utf8_encode($contents); 
  if(isset($_POST['username']) && isset($_POST['password']))
  {
      $username=$_POST['username'];
      $password=$_POST['password'];
      $response = array(); 
      $response['username'] = $username; 
      $response['password'] = $password;
      echo json_encode($response);
  }
  else{
       $no_data=array();
       $no_data['none']= 'no data received';
       echo json_encode($no_data);
  }
 ?>

Please let me know if it fixes your problem.

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

2 Comments

Thanks @Karim. That's exactly what i was looking for and I really appreciate your help in code suggestion and pointing out mistakes. Thank you very much.
I would suggest though that you look into your code as this method is deprecated. Look into url.openConnection for future methods and use json.

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.