4

我正在制作一个与远程服务器的数据库交互并通过传入和传出 JSON 对象来相互通信的 Android 应用程序。

我需要知道如何在我的服务器(最好是 PHP)上编写这样的服务,android 应用程序可以向它发出请求,并且在接收到请求时,服务器处理并制作一个 JSON 对象并将其传递给 android 应用程序。

另外,我需要知道,当此服务在服务器上运行时, android 应用程序将在哪个URL 上发出请求?

例如,如果 android 应用程序必须请求服务器以获取参数数据:名称:Apple 位置:US 那么,我猜 android 应用程序将必须以以下形式请求服务器:www.example.com?name='Apple "&location='美国'

那么如何让这样的服务在远程服务器上运行呢?

提前致谢 !

4

2 回答 2

9

您可以参考的最佳示例是http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/。它有完整的代码[php+ android],解释简单。

于 2012-09-19T10:41:01.687 回答
0

您可以编写一个请求远程 php 文件的方法,该文件响应 post 或 get 请求。如果你想使用 post request ,你可以使用下面的方法。并且您必须将 Internet 许可添加到清单文件中。如下所示,您可以将参数添加为键值对。

       public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/webservice.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("name", "Apple"));
    nameValuePairs.add(new BasicNameValuePair("locaction", "US"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    ResponseHandler <String> res=new BasicResponseHandler();  
    // Execute HTTP Post Request
    String response = httpclient.execute(httppost,res);


} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
  } 

http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

于 2012-09-19T10:32:03.240 回答