php返回数据到安卓 php返回数据到安卓系统

android怎么得到php发来的json数据

使用守则

创新互联公司主营东乌珠穆沁网站建设的网络公司,主营网站建设方案,成都APP应用开发,东乌珠穆沁h5微信小程序开发搭建,东乌珠穆沁网站营销推广欢迎东乌珠穆沁等地区企业咨询

首先,我们要创建Web服务,从MySQL数据库中读取数据。

?php

pre/* require the user as the parameter */

pre//

if(isset($_GET['user']) intval($_GET['user'])) {

/* soak in the passed variable or set our own */

$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default

$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default

$user_id = intval($_GET['user']); //no default

/* connect to the db */

$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');

mysql_select_db('TEST',$link) or die('Cannot select the DB');

/* grab the posts from the db */

//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =

// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";

$query = "SELECT * FROM `test`.`users`;";

$result = mysql_query($query,$link) or die('Errant query: '.$query);

/* create one master array of the records */

$posts = array();

if(mysql_num_rows($result)) {

while($post = mysql_fetch_assoc($result)) {

$posts[] = array('post'=$post);

}

}

/* output in necessary format */

if($format == 'json') {

header('Content-type: application/json');

echo json_encode(array('posts'=$posts));

}

else {

header('Content-type: text/xml');

echo '';

foreach($posts as $index = $post) {

if(is_array($post)) {

foreach($post as $key = $value) {

echo '',$key,'';

if(is_array($value)) {

foreach($value as $tag = $val) {

echo '',$tag,'',htmlentities($val),'/',$tag,'';

}

}

echo '/',$key,'';

}

}

}

echo '';

}

/* disconnect from the db */

@mysql_close($link);

}

?

下面是代码为Android活动读取Web服务和解析JSON对象:

public void clickbutton(View v) {

try {

//

// Log.i(getClass().getSimpleName(), "send task - start");

HttpParams httpParams = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParams,

TIMEOUT_MILLISEC);

HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

//

HttpParams p = new BasicHttpParams();

// p.setParameter("name", pvo.getName());

p.setParameter("user", "1");

// Instantiate an HttpClient

HttpClient httpclient = new DefaultHttpClient(p);

String url = "" +

"webservice1.php?user=1format=json";

HttpPost httppost = new HttpPost(url);

// Instantiate a GET HTTP method

try {

Log.i(getClass().getSimpleName(), "send task - start");

//

ListNameValuePair nameValuePairs = new ArrayListNameValuePair(

2);

nameValuePairs.add(new BasicNameValuePair("user", "1"));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

ResponseHandlerString responseHandler = new BasicResponseHandler();

String responseBody = httpclient.execute(httppost,

responseHandler);

// Parse

JSONObject json = new JSONObject(responseBody);

JSONArray jArray = json.getJSONArray("posts");

ArrayListHashMapString, String mylist =

new ArrayListHashMapString, String();

for (int i = 0; i jArray.length(); i++) {

HashMapString, String map = new HashMapString, String();

JSONObject e = jArray.getJSONObject(i);

String s = e.getString("post");

JSONObject jObject = new JSONObject(s);

map.put("idusers", jObject.getString("idusers"));

map.put("UserName", jObject.getString("UserName"));

map.put("FullName", jObject.getString("FullName"));

mylist.add(map);

}

Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// Log.i(getClass().getSimpleName(), "send task - end");

} catch (Throwable t) {

Toast.makeText(this, "Request failed: " + t.toString(),

Toast.LENGTH_LONG).show();

}

}

这里是PHP代码,将数据发送到Web服务,并将其保存:

?php

//$json=$_GET ['json'];

$json = file_get_contents('php://input');

$obj = json_decode($json);

//echo $json;

//Save

$con = mysql_connect('localhost','root','123456')

or die('Cannot connect to the DB');

mysql_select_db('TEST',$con);

/* grab the posts from the db */

//$query = "SELECT post_title, guid FROM wp_posts WHERE

// post_author = $user_id AND post_status = 'publish'

// ORDER BY ID DESC LIMIT $number_of_posts";

mysql_query("INSERT INTO `test`.`users` (UserName, FullName)

VALUES ('".$obj-{'UserName'}."', '".$obj-{'FullName'}."')");

mysql_close($con);

//

//$posts = array($json);

$posts = array(1);

header('Content-type: application/json');

echo json_encode(array('posts'=$posts));

?

Android的活动,将数据发送到Web服务作为一个JSON对象保存在MySQL数据库中

public void clickbuttonRecieve(View v) {

try {

JSONObject json = new JSONObject();

json.put("UserName", "test2");

json.put("FullName", "1234567"); HttpParams httpParams = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParams,

TIMEOUT_MILLISEC);

HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpClient client = new DefaultHttpClient(httpParams);

//

//String url = "?" +

// "json={\"UserName\":1,\"FullName\":2}";

String url = "";

HttpPost request = new HttpPost(url);

request.setEntity(new ByteArrayEntity(json.toString().getBytes(

"UTF8")));

request.setHeader("json", json.toString());

HttpResponse response = client.execute(request);

HttpEntity entity = response.getEntity();

// If the response does not enclose an entity, there is no need

if (entity != null) {

InputStream instream = entity.getContent();

String result = RestClient.convertStreamToString(instream);

Log.i("Read from server", result);

Toast.makeText(this, result,

Toast.LENGTH_LONG).show();

}

} catch (Throwable t) {

Toast.makeText(this, "Request failed: " + t.toString(),

Toast.LENGTH_LONG).show();

}

}

知识点

要连接到你的模拟器,你可以使用此链接:。

要读取JSON对象在Web服务中,您可以使用下面这行代码:

$json = file_get_contents('php://input');

$obj = json_decode($json);

PHP如何实施监控数据库的更新,一旦有更新,就把更新的数据推送给Android?

那你可以在插入数据库那里设置监听呀,一有插入就往Android推送消息。

不然你只能通过每隔一段时间刷新一下读取数据库,看看有没有更新,有就推送,没有就继续监听,这个你可以自己设置更新时间。

php服务器怎么接收安卓发送过来的数据

直接file_get_contents("php://input") 这个函数就可以接到接口传参,建议使用json格式数据进行交互。

安卓编程Volley框架发送post数据。php端$_POST接收不到数据,返回数据正常!

确定安卓端确实发送了数据-可以使用青花瓷Charles进行抓包查看。

确定php端写的代码没有问题-可以使用PostMan构造Post请求看看能不能接收到数据。

检查content-type头信息的类型

1.检查头信息content-type是不是为“content-type:application/x-www-form-urlencoded" 这种传输是以表单的方式提交数据php使用$_POST方式接受。

2.如果头信息content-type是不是为“content-type:application/json"这种传输是以json方式提交数据,php需要使用file_get_contents("php://input")获取输入流的方式接受

如何连接android和php mysql数据库

请注意:这里提供的代码只是为了使你能简单的连接Android项目和PHP,MySQL。你不能把它作为一个标准或者安全编程实践。在生产环境中,理想情况下你需要避免使用任何可能造成潜在注入漏洞的代码(比如MYSQL注入)。MYSQL注入是一个很大的话题,不可能用单独的一篇文章来说清楚,并且它也不在本文讨论的范围内,所以本文不以讨论。

1. 什么是WAMP Server

WAMP是Windows,Apache,MySQL和PHP,Perl,Python的简称。WAMP是一个一键安装的软件,它为开发PHP,MySQL Web应用程序提供一个环境。安装这款软件你相当于安装了Apache,MySQL和PHP。或者,你也可以使用XAMP。

2. 安装和使用WAMP Server

你可以从http://www。wampserver。com/en/下载WAMP,安装完成之后,可以从开始-所有程序-WampServer-StartWampServer运行该程序。

在浏览器中输入来测试你的服务器是否安装成功。同样的,也可以打开来检验phpmyadmin是否安装成功。

3. 创建和运行PHP项目

现在,你已经有一个能开发PHP和MYSQL项目的环境了。打开安装WAMP Server的文件夹(在我的电脑中,是C:\wamp\),打开www文件夹,为你的项目创建一个新的文件夹。你必须把项目中所有的文件放到这个文件夹中。

新建一个名为android_connect的文件夹,并新建一个php文件,命名为test.php,尝试输入一些简单的php代码(如下所示)。输入下面的代码后,打开,你会在浏览器中看到“Welcome,I am connecting Android to PHP,MySQL”(如果没有正确输入,请检查WAMP配置是否正确)

test.php

?php

echo"Welcome, I am connecting Android to PHP, MySQL";

?4. 创建MySQL数据库和表

在本教程中,我创建了一个简单的只有一张表的数据库。我会用这个表来执行一些示例操作。现在,请在浏览器中输入,并打开phpmyadmin。你可以用PhpMyAdmin工具创建数据库和表。

创建数据库和表:数据库名:androidhive,表:product

CREATE DATABASE androidhive;

CREATE TABLE products(

pid int(11) primary key auto_increment,

name varchar(100) not null,

price decimal(10,2) not null,

description text,

created_at timestamp defaultnow(),

updated_at timestamp

);5. 用PHP连接MySQL数据库

现在,真正的服务器端编程开始了。新建一个PHP类来连接MYSQL数据库。这个类的主要功能是打开数据库连接和在不需要时关闭数据库连接。

新建两个文件db_config.php,db_connect.php

db_config.php--------存储数据库连接变量

db_connect.php-------连接数据库的类文件

db_config.php

?php

/*

* All database connection variables

*/

define('DB_USER', "root"); // db user

define('DB_PASSWORD', ""); // db password (mention your db password here)

define('DB_DATABASE', "androidhive"); // database name

define('DB_SERVER', "localhost"); // db serverdb_connect.php

?php

/**

* A class file to connect to database

*/

classDB_CONNECT {

// constructor

function__construct() {

// connecting to database

$this-connect();

}

// destructor

function__destruct() {

// closing db connection

$this-close();

}

/**

* Function to connect with database

*/

functionconnect() {

// import database connection variables

require_once__DIR__ . '/db_config.php';

// Connecting to mysql database

$con= mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) ordie(mysql_error());

// Selecing database

$db= mysql_select_db(DB_DATABASE) ordie(mysql_error()) ordie(mysql_error());

// returing connection cursor

return$con;

}

/**

* Function to close db connection

*/

functionclose() {

// closing db connection

mysql_close();

}

}

?怎么调用:当你想连接MySQl数据库或者执行某些操作时,可以这样使用db_connect.php

$db= newDB_CONNECT(); // creating class object(will open database connection)

PHP网站怎么推送消息到安卓手机?

安卓上写个client保持与server的长连接,当有消息需要发送时走这个长连接就行。server必须维护所有用户的长连接,不然就不知道该给哪个设备发。客户端还需要解析消息的内容格式并显示。安卓机上所有有推送服务的都有一个名叫push service之类的东西。具体可以参考ios系统的apns服务


标题名称:php返回数据到安卓 php返回数据到安卓系统
文章来源:http://myzitong.com/article/hhogod.html