如何制作一个 Web 服务(最好使用 PHP),可以请求它来获取 android 应用程序 JSON 对象



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

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

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

例如,如果 android 应用必须请求服务器以获取参数数据:名称:苹果地点: 美国然后,我想Android应用程序将不得不以以下形式请求服务器: www.example.com?name='Apple"&location='US'

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

提前感谢!

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

您可以编写一个请求远程 php 文件的方法,以响应 post 或 get 请求。 如果要使用 POST 请求 ,可以使用以下方法。 并且您必须将互联网权限添加到清单文件中。如下所示,您可以将参数添加为键值对。

       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

最新更新