【问题标题】:sending JSON to server using POST in android app在 Android 应用程序中使用 POST 将 JSON 发送到服务器
【发布时间】:2014-06-20 11:19:55
【问题描述】:

我正在创建一个 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,则不会发生任何事情

但如果我尝试

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

从命令行它可以工作。

如果我尝试取消注释 $js = json_decode($_POST);在 PHP 脚本中添加一行并注释掉 php://input 行,那么 JSON 对象不会被传输,而是将值 "", 0,0 插入到数据库中

我认为应用程序代码一定有错误。我正在关注这里的教程和代码http://hmkcode.com/android-send-json-data-to-server/

问题

  1. 谁能解释我做错了什么以及一个可行的解决方案?
  2. php://input 和 $_POST 有什么区别?

谢谢

任务

【问题讨论】:

  • 你不能做 json_decode($_POST) 因为 $_POST 是一个数组。
  • @DenisV 谢谢,我是 PHP 新手,如何解码 JSON 对象?
  • 您正在发送“发布”请求,您可以在发布请求中获取数据。 PHP 代码如 $_POST...
  • @Rajnish 你能再具体一点吗?
  • @Gokul_uf 检查这个:stackoverflow.com/questions/8945879/…

标签: php android json curl


【解决方案1】:

使用此方法发出 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);

【讨论】:

  • 谢谢,就像一个魅力! :) 你能解释一下发生了什么以及我做错了什么吗?
【解决方案2】:

当您向服务器发送 post 请求时,您将在“Post”中获取参数(根据您的 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!";
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多