在Android应用程序中使用POST将JSON发送到服务器

时间:2014-06-20 11:19:55

标签: php android json curl

我正在创建一个Android应用程序,将JSON发送到服务器端的PHP脚本并将其存储在数据库中

这是来自应用

的相关代码
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;
}

这里是php脚本

 <?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);
?>

现在,如果尝试从应用程序中的对象发送JSON,则不会发生任何事情

但如果我尝试

卷曲-H&#34;内容类型:application / json&#34; -d&#39; {&#34; str&#34;:&#34; \&#34; hello \&#34;&#34;,&#34; lat&#34;:&#34; 3.1 #&34;,&#34; LON&#34;:&#34; 5.2&#34;}&#39;本地主机/ t2.php

从命令行开始工作。

此外,如果我尝试取消注释$ js = json_decode($ _ POST); PHP脚本中的行并注释掉php://输入行,然后不传输JSON对象,但将值&#34;&#34;,0,0插入到数据库中

我认为应用代码肯定存在错误。我正在遵循此处的教程和代码http://hmkcode.com/android-send-json-data-to-server/

问题

  1. 有人可以解释一下我做错了什么以及一个看似合理的解决方案吗?
  2. php:// input和$ _POST之间的区别是什么?
  3. 由于

    QUEST

2 个答案:

答案 0 :(得分:3)

使用此方法发出POST请求:

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;

}

用法:

在Java中:

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

String response = makePOSTRequest(String url, nameValuePairs );

服务器端Php:

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

答案 1 :(得分:0)

当您向服务器发送帖子请求时,您将在“发布”中获取参数。 (根据您的Android代码)。

这是解决方案:

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!";
}

希望上面的代码应该有用。