如何从Android调用PHP函数?

我想在服务器上调用特定的PHP函数,并发送一些参数。 直到现在我实现了我可以使用HttpClient打开php文件并执行数据传输到Json并在我的应用程序中显示。 所以,现在我希望能够调用特定的函数并向其发送参数,我该怎么做? 对不起我没有豪宅,我需要从Android调用该function。

这里有一些代码:

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 } 

在此先感谢,沃尔夫。

如果你正在使用一个MVC框架,比如CakePHP,你可以简单地创建一个到一个函数的路由,该函数将输出你想要的任何JSON。

否则,您可以在index.php的顶部使用简单的东西,例如:

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

这将允许您使用操作参数调用URL。

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

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

如果您需要传递更多敏感数据,我建议您坚持使用$ _POST并使用某种forms的加密。

你可以在PHP端处理它。 使用名为command的字段创建一个Json对象,可能还有一个参数列表。

在解码json之后的php端,只需:

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