在android应用中使用POST将JSON发送到服务器

在android应用中使用POST将JSON发送到服务器

本文介绍了在android应用中使用POST将JSON发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是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,则什么都不会发生

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

但如果我尝试

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

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插入数据库中

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

我认为应用程序代码一定有错误.我正在从此处 http://hmkcode.com/android-send-json-data-to-server/

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/

问题

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

谢谢

查询

推荐答案

使用此方法发出POST请求:

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;

}

用法:

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

这篇关于在android应用中使用POST将JSON发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:25