Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a simple Java client application (Android app). 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. 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? I have googled about SOAP and REST architectures, but looking for a simple tutorial which will allow me to implement this simple program.

Thanks.

like image 867
user245120 Avatar asked Feb 13 '10 22:02

user245120


2 Answers

With basic Java SE API you can use java.net.URLConnection to fire a HTTP request. A basic example of firing a GET request can be found in Sun tutorial on the subject. 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.

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.

If you want less verbose code and/or more control over the request, then I can recommend to use Apache Commons HttpComponents Client.

The PHP program in turn can just be written the usual way. Get request parameters by $_GET, $_POST and so on and echo the response. Nothing special needs to be done here. You may however consider to use an more easy parseable response format, such as XML or JSON.

like image 181
BalusC Avatar answered Oct 20 '22 23:10

BalusC


You should build a simple JSON or XML based REST web service with PHP.

Then with the Android SDK, you can use the HttpClient module to connect to your web service. The SDK also provide a JSON and XML module to parse the result.

like image 1
Desintegr Avatar answered Oct 20 '22 22:10

Desintegr