6

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
On running the script provided in the tutorial I am encountering the error as given on the page stackoverflow.com/questions/2543106/… but I am not able to guess the reason for the same.
One more solution of above was provided here at dtmilano.blogspot.com/2008/11/… but again this didn't help me out.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.