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

前端 未结 2 832
太阳男子
太阳男子 2020-12-15 13:28

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

相关标签:
2条回答
  • 2020-12-15 13:54

    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.

    0 讨论(0)
  • 2020-12-15 14:06

    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.

    0 讨论(0)
提交回复
热议问题