SAGA
SAGA

Reputation: 349

json object post to php script in android app

I tried this android code for send json objects to my website

HttpPost httppost = new HttpPost(url);

JSONObject j = new JSONObject();
    j.put("name","name ");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        String format = s.format(new Date()); 
    nameValuePairs.add(new BasicNameValuePair("msg",j.toString() ));

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                               httpclient.execute(httppost);

And this php code

<?php

$msg=$_POST["msg"]; 

$filename="androidmessages.html";

file_put_contents($filename,$msg."<br />",FILE_APPEND);

$androidmessages=file_get_contents($filename);

echo $androidmessages;
?>

It will show me {"name":"name "} but if i use

httppost.setHeader( "Content-Type", "application/json" );

it will show nothing.I have no before experince about json object post but i think something went wrong.I want to send some user information to my website and display it in web page can you please tell me what i need to change to overcome this problem Thank you

Upvotes: 3

Views: 2555

Answers (2)

SAGA
SAGA

Reputation: 349

Finally i got the answer

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

$filename="androidmessages_json.html";

file_put_contents($filename,$msg['name']."<br />",FILE_APPEND); 

$androidmessages=file_get_contents($filename);

echo $androidmessages;

Upvotes: 2

Christian
Christian

Reputation: 4641

It depends how you want to pass the data to your PHP-script.

If you want to get the JSON as a string in one variable (and maybe others in addition), then you should not use the content-type "application/json". If you want to only post the JSON without any variable, you can do the following instead:

HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
httppost.setEntity(new StringEntity(j.toString());
httpclient.execute(httppost);

As you can imagine from the code you do not have the JSON in one POST-var only but in total.

Upvotes: 1

Related Questions