简体   繁体   中英

sending JSON to server using POST in android app

I'm creating an android app to send JSON to a server-side php script and store it in a database

Here's the relevant code from the app

public String POST(){
    String url = "http://192.168.150.1/t2.php";
    InputStream inputStream = null;
    String result = "";
    try {

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        String json = "";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("str", "bang");
        jsonObject.put("lat", 3.10);
        jsonObject.put("lon", 3.10);

        json = jsonObject.toString();
        Toast.makeText(this, json, Toast.LENGTH_LONG).show();

        StringEntity se = new StringEntity(json);


        httpPost.setEntity(se);


        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");


        HttpResponse httpResponse = httpclient.execute(httpPost);


        inputStream = httpResponse.getEntity().getContent();



        if(inputStream != null)
            result = "success";
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }


    return result;
}

and here's the php script

 <?php

    $connection = mysql_connect("192.168.150.1","****","****"); 
    if (!$connection) {
        die("Database connection failed: " . mysql_error());
    }
         echo "connection success\n";
        $db_select = mysql_select_db("ps1",$connection);
    if (!$db_select) {
        die("Database selection failed: " . mysql_error());
    }
    echo "db selections success";
?>
<html>
    <head>
        <title> hl</title>
    </head>
    <body>
    <p>hello</p>    
<?php


$js = json_decode(file_get_contents('php://input'));    
 //$js = json_decode($_POST); ------------ ******
$atr ='';
$val = '';
foreach ($js as $a => $v)
{
 $atr = $atr.','.$a;
 $val = $val.','.$v;
}


$atr = ltrim($atr,',');
$val = ltrim($val,',');

echo "insert into js (".$atr.") values (" .$val . ");";
$result = mysql_query("insert into js (".$atr.") values (" .$val . ");", $connection);
    if (!$result) {
        die("Database query failed: " . mysql_error());
    }       
    ?>

    </body>
</html>
<?php

    mysql_close($connection);
?>

Now if try to send a JSON from object from the app, nothing happens

but if I try

curl -H "Content-Type: application/json" -d '{"str":"\\"hello\\"","lat":"3.1","lon":"5.2"}' localhost/t2.php

from the command-line it works.

Also if I try to uncomment the $js = json_decode($_POST); line in the PHP script and comment out the php://input line, then the JSON object is not transferred but the values "", 0,0 are inserted into the database

I think there must be an error with the app code.I'm following the tutorial and code from here http://hmkcode.com/android-send-json-data-to-server/

QUESTIONS

  1. Can someone explain what I'm doing wrong and a plausible solution?
  2. what's the difference between php://input and $_POST?

Thanks

QUEST

Use this method to make POST Request :

public String makePOSTRequest(String url, List<NameValuePair> nameValuePairs) {
    String response = "";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d(LOGTAG, "POST Response >>> " + response);
    return response;

}

Usage :

In Java :

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsonObject.toString()));

String response = makePOSTRequest(String url, nameValuePairs );

Server Side Php :

$jsonInput = $_POST['json'];
json_decode($jsonInput);

When you send post request to server you will get parameters in 'Post' (as per your android code).

Here is solution:

if($_POST)
{
  foreach ($js as $a => $v)
  {
    $atr = $atr.','.$a;
    $val = $val.','.$v;
  }

 $atr = ltrim($atr,',');
 $val = ltrim($val,',');

 echo "insert into js (".$atr.") values (" .$val . ");";

 $result = mysql_query("insert into js (".$atr.") values (" .$val . ");", $connection);
 if (!$result) {
    die("Database query failed: " . mysql_error());
 }     
}
else
{
  echo "Please send data in HTTP POST REQUEST!";
}

Hope above code should be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM