如何实现Java客户端应用程序(安卓)和PHP服务器应用程序之间的通信? [英] How to implement communication between Java client application (Android) and PHP server application?

查看:123
本文介绍了如何实现Java客户端应用程序(安卓)和PHP服务器应用程序之间的通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Java客户端应用程序(Android应用程序)。我必须写它接收来自Java客户端应用程序写入一些数据到MySQL数据库或MySQL数据库读取一些数据的请求的PHP服务器应用程序。它应该响应分别请求状态消息(写失败/成功)或数据。

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.

我该如何获得Java客户端发送请求并接收来自PHP程序的答复,以及如何将PHP程序接收请求和发送应答?我用Google搜索有关SOAP和REST的架构,而是在寻找一个简单的教程,这将让我实现这个简单的程序。

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.

感谢。

推荐答案

使用基本的Java SE API,你可以使用<一个href="http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html"><$c$c>java.net.URLConnection火一个HTTP请求。烧制 GET 要求的一个基本的例子可以的关于这个问题的太阳教程。 A POST 要求是没有太大的不同,你不是只需要设置<一个href="http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html#setDoOutput%28boolean%29"><$c$c>URLConnection#setDoOutput(),写的查询字符串<一个href="http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html#getOutputStream%28%29"><$c$c>URLConnection#getOutputStream()而不是在URL。

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.

请注意,它的懒洋洋地执行,请求才会被解雇,如果你真的通过<一个获得响应流href="http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html#getInputStream%28%29"><$c$c>URLConnection#getInputStream(),即使你不需要它。

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.

如果你想更简洁code和/或在要求更多的控制权,那么我可以推荐使用 Apache的百科全书HttpComponents客户端

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

依次PHP程序可以只写在通常的方式。通过 $ _ GET $ _ POST 等和回声的响应。没什么特别需要在这里完成。不过,您可以考虑使用一个更简单的解析的响应格式,如XML或JSON。

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.

这篇关于如何实现Java客户端应用程序(安卓)和PHP服务器应用程序之间的通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆