从android发送数据到PHP

时间:2014-01-17 12:06:58

标签: java php android json

我在从android向php脚本发送数据时遇到问题。我在网上搜索了为什么它没有工作但没有答案工作的答案。我也试过用$ _ GET和$ _SERVER但它也不起作用。我有什么错误吗? Android代码:

int timout = 10000;
       try {
           JSONObject json = new JSONObject();
           json.put("skola", regid);
           Log.w("test","json array== "+json);
           HttpParams httpParams = new BasicHttpParams();
           HttpConnectionParams.setConnectionTimeout(httpParams,
                   timout);
           HttpConnectionParams.setSoTimeout(httpParams, timout);
           HttpClient client = new DefaultHttpClient(httpParams);

           HttpPost request = new HttpPost(url);
           request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                   "UTF8")));
           request.setHeader("json", json.toString());
           HttpResponse response = client.execute(request);
           HttpEntity entity = response.getEntity();

           if (entity != null) {
               InputStream instream = entity.getContent();

               String result = convertStreamToString(instream);
               Log.i("Read from server", result);
               Toast.makeText(SettingsActivity.this,  result,
                       Toast.LENGTH_LONG).show();
           }
       } catch (Throwable t) {
           Toast.makeText(SettingsActivity.this, "Request failed: " + t.toString(),
                   Toast.LENGTH_LONG).show();
       }

和我的PHP代码:

<?php

$obj=$_POST['json'];
$db=json_decode($obj,true);

file_put_contents('myTextFile.txt',$db);


$con = mysql_connect("localhost","avg","1zmaInas");
mysql_select_db("datubazes", $con); 
mysql_query ("set character_set_client='utf8'");
mysql_query ("set character_set_results='utf8'");
mysql_query ("set collation_connection='utf8_general_ci'");
mysql_query ("SET NAMES utf8");
    $result = mysql_query("SELECT * FROM saraksts WHERE skola='$db' ");
    while($row = mysql_fetch_assoc($result))
  { 
    $db=$row['datubaze'];
  }
$con = mysql_connect("localhost","avg","1zmaInas");

    mysql_select_db($db, $con); 
    $result = mysql_query("SELECT klase FROM klases");
    while($row = mysql_fetch_assoc($result))
  { 
    $output[]=$row;
  }
print(json_encode($output));
mysql_close($con);
?>

1 个答案:

答案 0 :(得分:0)

我认为您将json数据设置为header,然后尝试将其作为POST数据读取。

此行将JSON设置为名为“json”的HEADER:

request.setHeader("json", json.toString());

PHP行试图将json字符串作为POST数据:

$obj=$_POST['json'];

总结:标题与POST字段不同。

您从PHP脚本中看到了哪些标题?

查看有关发布数据的答案:Sending POST data in Android