views:

902

answers:

2

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.

+3  A: 

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.

BalusC
Let us suppose that we have sent a HTTP request to the PHP program which receives the $_GET/$_POST parameters, does some processing and wants to echo back a string "Processing successful". Do I just simply do echo $string and the Java program will receive it in URLConnection's InputStream ?
That's correct.
BalusC
+1  A: 

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.

Desintegr