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!