Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recive JSON object in a PHP script from Android

Tags:

json

android

php

This is my first time developing a PHP site with JSON and also working with a online database from a Android device, my problem is that I don't know why my script returns null, I haven't send it any variables at all.

My PHP code is:

<?php

 $data = file_get_contents('php://input');
 $json = json_decode($data, true);

 var_dump($json);

?>

The question is: Which is the way to collect the JSON data that the Android Device has send to my php?

If some one asks that is the way I send the data from my Android Device to the php:

In my android app I send the JSON object this way:

    HttpResponse response =null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
         HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),3000);

    HttpPost request = new HttpPost(url);

    StringEntity se = new StringEntity(json.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
            "application/json"));
    try{
     response = httpClient.execute(request);
    }catch(SocketException sE)
    {
        throw sE;
    }

The structure of data that I'm sending from my android code is the following one:

JSONObject json = new JSONObject();
try {
        json.put("user", 0);
        json.put("status", "Confirmed");
 } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
 }
like image 244
ALanao Avatar asked Dec 07 '25 07:12

ALanao


1 Answers

I found the solution to the problem, thanks to the comment of Mike Miller.

The problem wasn't in the PHP, was in the android app because i wasn't sending anything from the Android Device.

So the correct solution will be that one:

    HttpResponse response =null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),3000);

    HttpPost request = new HttpPost(url);

    //Adding a header for the string
    request.setHeader("json", json.toString());

    StringEntity se = new StringEntity(json.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
            "application/json"));

    //adding the StringEntitu to the request
    request.setEntity(se);

    try{
        response = httpClient.execute(request);
    }
    catch(SocketException sE)
    {
        Log.e("SocketException", sE+"");
        throw sE;
    }

Thanks a lot every one, who have help me!

like image 57
ALanao Avatar answered Dec 08 '25 21:12

ALanao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!