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

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

问题描述

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



我如何让Java客户端发送请求并接收来自PHP程序,PHP程序如何接收请求并发送回复?我已经了解SOAP和REST架构,但是寻找一个简单的教程,这将允许我实现这个简单的程序。



谢谢。

解决方案

使用基本的Java SE API,您可以使用 java.net.URLConnection 以触发HTTP请求。触发 GET 请求的基本示例可以在 Sun教程。 A POST 请求没有太大的不同,你只需要设置 URLConnection#setDoOutput() true ,并将查询字符串写入 URLConnection#getOutputStream()



请注意,它是延迟执行,请求将只会触发,如果你实际获得响应流 URLConnection#getInputStream() ,即使您不需要它。 / p>

如果你想要更少的详细代码和/或更多的控制请求,那么我可以推荐使用 Apache Commons HttpComponents客户端



PHP程序可以按照通常的方式编写。通过 $ _ GET $ _ POST 等等获取请求参数,以及 echo 响应。这里没有什么特别的需要做。但您可以考虑使用更容易的可解析响应格式,例如XML或JSON。


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.

解决方案

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.

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

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