简体   繁体   English

如何实现Java客户端应用程序(Android)和PHP服务器应用程序之间的通信?

[英]How to implement communication between Java client application (Android) and PHP server application?

I have a simple Java client application (Android app). 我有一个简单的Java客户端应用程序(Android应用程序)。 I have to write a PHP server application which receives a request from the Java client application to write some data to a MySQL database or read some data from the MySQL database. 我必须编写一个PHP服务器应用程序,它接收来自Java客户端应用程序的请求,将一些数据写入MySQL数据库或从MySQL数据库中读取一些数据。 It should respond with a status message (Write failed/success) or the data requested respectively. 它应该响应状态消息(写入失败/成功)或分别请求的数据。

How would I get the Java client send a request and receive the reply from the PHP program and how would the PHP program receive the request and send the reply? 我如何让Java客户端发送请求并从PHP程序接收回复?PHP程序将如何接收请求并发送回复? I have googled about SOAP and REST architectures, but looking for a simple tutorial which will allow me to implement this simple program. 我已经搜索了SOAP和REST架构,但是寻找一个简单的教程,这将允许我实现这个简单的程序。

Thanks. 谢谢。

With basic Java SE API you can use java.net.URLConnection to fire a HTTP request. 使用基本Java SE API,您可以使用java.net.URLConnection来触发HTTP请求。 A basic example of firing a GET request can be found in Sun tutorial on the subject . 触发GET请求的基本示例可以在关于该主题的Sun教程中找到。 A POST request isn't much different, you instead just need to set URLConnection#setDoOutput() to true and write the query string to URLConnection#getOutputStream() instead of in URL. POST请求没有太大区别,您只需要将URLConnection#setDoOutput()true ,并将查询字符串写入URLConnection#getOutputStream()而不是URL。

Note that it's "lazily executed", the request will only be fired if you actually obtain the response stream by URLConnection#getInputStream() , even though you don't need it. 请注意,它是“懒惰地执行”,只有在您实际通过URLConnection#getInputStream()获取响应流时才会触发请求,即使您不需要它。

If you want less verbose code and/or more control over the request, then I can recommend to use Apache Commons HttpComponents Client . 如果您想要更少的冗长代码和/或更多控制请求,那么我可以建议使用Apache Commons HttpComponents Client

The PHP program in turn can just be written the usual way. 反过来,PHP程序可以用通常的方式编写。 Get request parameters by $_GET , $_POST and so on and echo the response. 通过$_GET$_POST等获取请求参数并echo显响应。 Nothing special needs to be done here. 这里没有什么特别需要做的。 You may however consider to use an more easy parseable response format, such as XML or JSON. 但是,您可以考虑使用更简单的可解析响应格式,例如XML或JSON。

You should build a simple JSON or XML based REST web service with PHP. 您应该使用PHP构建一个简单的基于JSON或XML的REST Web服务。

Then with the Android SDK, you can use the HttpClient module to connect to your web service. 然后使用Android SDK,您可以使用HttpClient模块连接到您的Web服务。 The SDK also provide a JSON and XML module to parse the result. SDK还提供了一个JSONXML模块来解析结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM