How to implement a connection between a Java (Android) client application and a PHP server application?

I have a simple Java client application (Android app). I have to write a PHP server application that receives a request from a Java client application to write some data to a MySQL database or read some data from a MySQL database. It should respond with a status message (Write Error / Success) or the requested data, respectively.

How can I get a Java client to send a request and receive a response from a PHP program, and how will a PHP program receive a request and send a response? I googled about SOAP and REST architectures, but are looking for a simple tutorial that will allow me to implement this simple program.

Thanks.

+6
java android php client-server
source share
2 answers

With the basic Java SE API, you can use java.net.URLConnection to trigger an HTTP request. A basic example of running a GET request can be found in Sun's tutorial on this . The POST request is not much different, instead you just need to set URLConnection#setDoOutput() to true and write the request string in URLConnection#getOutputStream() instead of the URL.

Please note that it is "lazily executed", the request will be launched only if you really get the response stream URLConnection#getInputStream() , although you do not need it.

If you need less verbose code and / or more control over the request, I can recommend using the Apache Commons HttpComponents Client .

In turn, a PHP program can simply be written in the usual way. Get request parameters $_GET , $_POST , etc. And echo answer. Nothing special is needed here. However, you can use a simpler parsing format like XML or JSON.

+6
source share

You must create a simple JSON or XML based REST web service with PHP.

Then, with the Android SDK, you can use HttpClient to connect to your web service. The SDK also provides JSON and XML for parsing the result.

+1
source share

All Articles