3

我想在服务器上调用特定的 php 函数并发送一些参数。到目前为止,我已经实现了可以使用 HttpClient 打开 php 文件并将数据传输到 Json 并在我的应用程序中显示出来。所以,现在我希望能够调用特定的函数并向它发送参数,我该怎么做呢?抱歉,我不认为我需要从 Android 调用该函数。

这里有一些代码:

try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/posloviPodaci/index.php");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,   "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            while((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // Parsing data
        JSONArray jArray;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;

            items = new String[jArray.length()];

            for(int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                items[i] = json_data.getString("naziv");
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

在此先感谢,狼。

4

2 回答 2

1

If you are working with an MVC framework, such as CakePHP, you can simply create a route to a function that will output whatever JSON you'd like.

Otherwise, You can utilize something simple at the top of your index.php such as this:

<?php
   function foo($bar) { echo $bar; }
   if(isset($_GET['action']) && (strlen($_GET['action']) > 0)) {
      switch($_GET['action']) :
         case 'whatever':
            echo json_encode(array('some data'));
            break;
         case 'rah':
            foo(htmlentities($_GET['bar']));
            break;
      endswitch;
      exit; # stop execution.
   }
?>

This will let you call the url with a parameter of action.

http://10.0.2.2/posloviPodaci/index.php?action=whatever

http://10.0.2.2/posloviPodaci/index.php?action=rah&bar=test

If you need to pass more sensitive data, I recommend you stick with $_POST and utilize some form of encryption.

于 2012-04-24T16:30:06.413 回答
-1

你可以在 php 端处理它。创建一个 Json 对象,其中包含一个名为 command 的字段,可能还有一个参数列表。

在解码 json 后的 php 端,只需执行以下操作:

if($obj.command == "foo"){
  foo($obj.arg[0],$obj.arg[1]);

}
于 2012-04-24T16:34:11.653 回答