安卓phpjson数据 安卓php环境搭建

php和安卓怎么实现数据(如json)交互

PHP是一种创建动态交互性站点的服务器端脚本语言,优势:PHP脚本语言应用广泛,开源免费,最重要的是入门简单,容易掌握。PHP能够生成动态页面内容PHP能够创建、打开、读取、写入、删除以及关闭服务器上的文件PHP能够接收表单数据PHP能够发送并取回cookiesPHP能够添加、删除、修改数据库中的数据PHP能够限制用户访问网站中的某些页面能够运行于各种平台,几乎兼容所有WEB服务器,支持多种数据库1.我们想要运行PHP,首先要有个web服务器,一般可以在本地部署一个服务器用来测试。所以需要下载个XAMPP,我们在百度搜索apache friends,直接打开第一个链接,然后毫不犹豫的下载最新版本(PHP7.0.9),下载后执行安装。2.2.现在来配置XAMPP来部署一个本地服务器,打开只需要启用Apache服务,下面我就启动成功了。如果启用不成功,Port(s)没有数据显示,就证明你监听的PC端口被占用,你可以在Config的里第一个选项进行监听端口的更改,找到记事本里的Listen 8080命令改后缀,这里我把监听端口改成空闲的8080了。3.下面来打开Dreamweaver建一个服务器站点。站点配置:本地站点文件夹一定要选择你装Xampp路径的htdocs的目录里。4.添加服务器配置:这样站点就设置好了,然后在站点文件夹创建server.php,脚本如下?php //设置页面内容是html编码格式是utf-8 //header("Content-Type: text/plain;charset=utf-8"); header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,GET'); header('Access-Control-Allow-Credentials:true'); header("Content-Type: application/json;charset=utf-8"); //header("Content-Type: text/xml;charset=utf-8"); //header("Content-Type: text/html;charset=utf-8"); //header("Content-Type: application/javascript;charset=utf-8"); //定义一个多维数组,包含员工的信息,每条员工信息为一个数组 $staff = array ( array("name" = "乔布斯", "number" = "101", "sex" = "男", "job" = "IOS开发工程师"), array("name" = "比尔盖茨", "number" = "102", "sex" = "男", "job" = "微软开发工程师"), array("name" = "陈美丽", "number" = "103", "sex" = "女", "job" = "安卓开发工程师"), array("name" = "黄力", "number" = "104", "sex" = "男", "job" = "Java开发工程师"), array("name" = "车神", "number" = "105", "sex" = "男", "job" = "游戏开发工程师"), array("name" = "测试猫", "number" = "106", "sex" = "男", "job" = "web前端开发工程师") ); //判断如果是get请求,则进行搜索;如果是POST请求,则进行新建 //$_SERVER是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字 //$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法 if ($_SERVER["REQUEST_METHOD"] == "GET") { search(); } elseif ($_SERVER["REQUEST_METHOD"] == "POST"){ create(); } //通过员工编号搜索员工 function search(){ //检查是否有员工编号的参数 //isset检测变量是否设置;empty判断值为否为空 //超全局变量 $_GET 和 $_POST 用于收集表单数据 if (!isset($_GET["number"]) empty($_GET["number"])) { echo '{"success":false,"msg":"参数错误"}'; return; } //函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。 //global 关键词用于访问函数内的全局变量 global $staff; //获取number参数 $number = $_GET["number"]; $result = '{"success":false,"msg":"没有找到员工。"}'; //遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果 foreach ($staff as $value) { if ($value["number"] == $number) { $result = '{"success":true,"msg":"找到员工:员工编号:' . $value["number"] . ',员工姓名:' . $value["name"] . ',员工性别:' . $value["sex"] . ',员工职位:' . $value["job"] . '"}'; break; } } echo $result; } //创建员工 function create(){ //判断信息是否填写完全 if (!isset($_POST["name"]) empty($_POST["name"]) !isset($_POST["number"]) empty($_POST["number"]) !isset($_POST["sex"]) empty($_POST["sex"]) !isset($_POST["job"]) empty($_POST["job"])) { echo '{"success":false,"msg":"参数错误,员工信息填写不全"}'; return; } //TODO: 获取POST表单数据并保存到数据库 //提示保存成功 echo '{"success":true,"msg":"员工:' . $_POST["name"] . ' 信息保存成功!"}'; } ? 我们可以在server.php文件数组$staff里的数据进行查询,并且可以实现添加数据的功能,下面来创建demo.htmlstyle body,input,button,select,h1{ font-size:20px; line-height:18px; } /style script window.onload=function(){ document.getElementById("search").onclick=function(){//查询数据 //发送Ajax查询请求并处理 var request=new XMLHttpRequest(); //open("方法(GET查询,POST添加)","打开的文件数据",处理方式(同步为false异步为true,不填默认为true)); request.open("GET","server.php?number="+document.getElementById('keyword').value); request.send(); request.onreadystatechange=function(){ if(request.readyState===4){//当服务器请求完成 if(request.status===200){//status==200为服务器请求成功 var data=JSON.parse(request.responseText); if(data.success){//数据填写符合要求 document.getElementById('searchResult').innerHTML=data.msg; }else{//数据填写不符号要求 document.getElementById('searchResult').innerHTML="出现错误:"+data.msg; } }else{//服务器请求失败 alert("发生错误:"+request.status); } } } } document.getElementById("save").onclick=function(){//添加数据 //发送Ajax添加数据请求并处理 var request=new XMLHttpRequest(); //open("方法(GET查询,POST添加)","打开的文件数据",处理方式(同步为false异步为true,不填默认为true));; request.open("POST","server.php"); //定义data取得用户所填写的数据,并且send(data)到服务器 var data="name="+document.getElementById("staffName").value +"number="+document.getElementById("staffNumber").value +"sex="+document.getElementById("staffSex").value +"job="+document.getElementById("staffJob").value; request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//在POST方法里必写,否则添加数据不起作用 request.send(data); request.onreadystatechange=function(){ if(request.readyState===4){//当服务器请求完成 if(request.status===200){//status==200为服务器请求成功 var data=JSON.parse(request.responseText); if(data.success){//数据填写符合要求 document.getElementById('createResult').innerHTML=data.msg; }else{//数据填写不符合要求 document.getElementById('createResult').innerHTML="出现错误:"+data.msg; } }else{//服务器请求失败 alert("发生错误:"+request.status); } } } } } /script body h1员工查询/h1 label请输入员工编号:/label input type="text" id="keyword"/ button id="search"查询/button p id="searchResult"/p h1员工创建/h1 label请输入员工姓名:/label input type="text" id="staffName"/br label请输入员工编号:/label input type="text" id="staffNumber"/br label请输入员工性别:/label select id="staffSex" option男/option option女/option /selectbr label请输入员工职位:/label input type="text" id="staffJob"/br button id="save"保存/button p id="createResult"/p /body 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

新乡县ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

如何使用JSON连接Android和PHP Mysql数据库

Android客户端直接连接远程MySQL数据库的方法如下:String result = ""; //首先使用NameValuePair封装将要查询的年数和关键字绑定 ArrayListNameValuePair nameValuePairs = new ArrayListNameValuePair(); nameValuePairs/getAllPeopleBornAfter.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //将HttpEntity转化为String try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close();result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); }//将String通过JSONArray解析成最终结果 try{ JSONArray jArray = new JSONArray(result); for(int i=0;ijArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","id: "+json_data.getInt("id")+ ", name: "+json_data.getString("name")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("birthyear") ); } } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); }虽然Android开发中可以直接连接数据库,但是实际中却不建议这么做,应该使用服务器端中转下完成。

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

使用守则

首先,我们要创建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);


网页题目:安卓phpjson数据 安卓php环境搭建
文章分享:http://cdiso.cn/article/ddjdijj.html

其他资讯