I want to sent the data from an Android device to PHP. I have tried but where I am wrong I don’t know. How do I correct this?
This is the Android code that I have done.
public class php_connect extends Activity {
InputStream is;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
JSONObject json = new JSONObject();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/food/food.php");
json.put("id",1);
json.put("name","john");
Log.i("jason Object", json.toString());
httppost.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Toast.makeText(getApplicationContext(),String.valueOf(statusCode), Toast.LENGTH_SHORT).show();
is = se.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "Successfully Connected", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Fail to Connect", Toast.LENGTH_SHORT).show();
}
}
}
I get response as 200 and connected successfully but cannot see data in PHP.
And my PHP code is:
<?php
$data = file_get_contents('php://input');
$json = json_decode($data,true);
var_dump($json);
$id=$json['id'];
echo $id;
?>
I always get the null result.
From the PHP manual:
I think it will be even easier to encode your JSON as a form parameter and use the normal PHP $_POST function to read it:
On the PHP side you can simply do
Note: I have not tested the above code.