真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

安卓phpjson數(shù)據(jù) 安卓php環(huán)境搭建

php和安卓怎么實(shí)現(xiàn)數(shù)據(jù)(如json)交互

PHP是一種創(chuàng)建動(dòng)態(tài)交互性站點(diǎn)的服務(wù)器端腳本語(yǔ)言,優(yōu)勢(shì):PHP腳本語(yǔ)言應(yīng)用廣泛,開源免費(fèi),最重要的是入門簡(jiǎn)單,容易掌握。PHP能夠生成動(dòng)態(tài)頁(yè)面內(nèi)容PHP能夠創(chuàng)建、打開、讀取、寫入、刪除以及關(guān)閉服務(wù)器上的文件PHP能夠接收表單數(shù)據(jù)PHP能夠發(fā)送并取回cookiesPHP能夠添加、刪除、修改數(shù)據(jù)庫(kù)中的數(shù)據(jù)PHP能夠限制用戶訪問(wèn)網(wǎng)站中的某些頁(yè)面能夠運(yùn)行于各種平臺(tái),幾乎兼容所有WEB服務(wù)器,支持多種數(shù)據(jù)庫(kù)1.我們想要運(yùn)行PHP,首先要有個(gè)web服務(wù)器,一般可以在本地部署一個(gè)服務(wù)器用來(lái)測(cè)試。所以需要下載個(gè)XAMPP,我們?cè)诎俣人阉鱝pache friends,直接打開第一個(gè)鏈接,然后毫不猶豫的下載最新版本(PHP7.0.9),下載后執(zhí)行安裝。2.2.現(xiàn)在來(lái)配置XAMPP來(lái)部署一個(gè)本地服務(wù)器,打開只需要啟用Apache服務(wù),下面我就啟動(dòng)成功了。如果啟用不成功,Port(s)沒有數(shù)據(jù)顯示,就證明你監(jiān)聽的PC端口被占用,你可以在Config的里第一個(gè)選項(xiàng)進(jìn)行監(jiān)聽端口的更改,找到記事本里的Listen 8080命令改后綴,這里我把監(jiān)聽端口改成空閑的8080了。3.下面來(lái)打開Dreamweaver建一個(gè)服務(wù)器站點(diǎn)。站點(diǎn)配置:本地站點(diǎn)文件夾一定要選擇你裝Xampp路徑的htdocs的目錄里。4.添加服務(wù)器配置:這樣站點(diǎn)就設(shè)置好了,然后在站點(diǎn)文件夾創(chuàng)建server.php,腳本如下?php //設(shè)置頁(yè)面內(nèi)容是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"); //定義一個(gè)多維數(shù)組,包含員工的信息,每條員工信息為一個(gè)數(shù)組 $staff = array ( array("name" = "喬布斯", "number" = "101", "sex" = "男", "job" = "IOS開發(fā)工程師"), array("name" = "比爾蓋茨", "number" = "102", "sex" = "男", "job" = "微軟開發(fā)工程師"), array("name" = "陳美麗", "number" = "103", "sex" = "女", "job" = "安卓開發(fā)工程師"), array("name" = "黃力", "number" = "104", "sex" = "男", "job" = "Java開發(fā)工程師"), array("name" = "車神", "number" = "105", "sex" = "男", "job" = "游戲開發(fā)工程師"), array("name" = "測(cè)試貓", "number" = "106", "sex" = "男", "job" = "web前端開發(fā)工程師") ); //判斷如果是get請(qǐng)求,則進(jìn)行搜索;如果是POST請(qǐng)求,則進(jìn)行新建 //$_SERVER是一個(gè)超全局變量,在一個(gè)腳本的全部作用域中都可用,不用使用global關(guān)鍵字 //$_SERVER["REQUEST_METHOD"]返回訪問(wèn)頁(yè)面使用的請(qǐng)求方法 if ($_SERVER["REQUEST_METHOD"] == "GET") { search(); } elseif ($_SERVER["REQUEST_METHOD"] == "POST"){ create(); } //通過(guò)員工編號(hào)搜索員工 function search(){ //檢查是否有員工編號(hào)的參數(shù) //isset檢測(cè)變量是否設(shè)置;empty判斷值為否為空 //超全局變量 $_GET 和 $_POST 用于收集表單數(shù)據(jù) if (!isset($_GET["number"]) empty($_GET["number"])) { echo '{"success":false,"msg":"參數(shù)錯(cuò)誤"}'; return; } //函數(shù)之外聲明的變量擁有 Global 作用域,只能在函數(shù)以外進(jìn)行訪問(wèn)。 //global 關(guān)鍵詞用于訪問(wèn)函數(shù)內(nèi)的全局變量 global $staff; //獲取number參數(shù) $number = $_GET["number"]; $result = '{"success":false,"msg":"沒有找到員工。"}'; //遍歷$staff多維數(shù)組,查找key值為number的員工是否存在,如果存在,則修改返回結(jié)果 foreach ($staff as $value) { if ($value["number"] == $number) { $result = '{"success":true,"msg":"找到員工:?jiǎn)T工編號(hào):' . $value["number"] . ',員工姓名:' . $value["name"] . ',員工性別:' . $value["sex"] . ',員工職位:' . $value["job"] . '"}'; break; } } echo $result; } //創(chuàng)建員工 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":"參數(shù)錯(cuò)誤,員工信息填寫不全"}'; return; } //TODO: 獲取POST表單數(shù)據(jù)并保存到數(shù)據(jù)庫(kù) //提示保存成功 echo '{"success":true,"msg":"員工:' . $_POST["name"] . ' 信息保存成功!"}'; } ? 我們可以在server.php文件數(shù)組$staff里的數(shù)據(jù)進(jìn)行查詢,并且可以實(shí)現(xiàn)添加數(shù)據(jù)的功能,下面來(lái)創(chuàng)建demo.htmlstyle body,input,button,select,h1{ font-size:20px; line-height:18px; } /style script window.onload=function(){ document.getElementById("search").onclick=function(){//查詢數(shù)據(jù) //發(fā)送Ajax查詢請(qǐng)求并處理 var request=new XMLHttpRequest(); //open("方法(GET查詢,POST添加)","打開的文件數(shù)據(jù)",處理方式(同步為false異步為true,不填默認(rèn)為true)); request.open("GET","server.php?number="+document.getElementById('keyword').value); request.send(); request.onreadystatechange=function(){ if(request.readyState===4){//當(dāng)服務(wù)器請(qǐng)求完成 if(request.status===200){//status==200為服務(wù)器請(qǐng)求成功 var data=JSON.parse(request.responseText); if(data.success){//數(shù)據(jù)填寫符合要求 document.getElementById('searchResult').innerHTML=data.msg; }else{//數(shù)據(jù)填寫不符號(hào)要求 document.getElementById('searchResult').innerHTML="出現(xiàn)錯(cuò)誤:"+data.msg; } }else{//服務(wù)器請(qǐng)求失敗 alert("發(fā)生錯(cuò)誤:"+request.status); } } } } document.getElementById("save").onclick=function(){//添加數(shù)據(jù) //發(fā)送Ajax添加數(shù)據(jù)請(qǐng)求并處理 var request=new XMLHttpRequest(); //open("方法(GET查詢,POST添加)","打開的文件數(shù)據(jù)",處理方式(同步為false異步為true,不填默認(rèn)為true));; request.open("POST","server.php"); //定義data取得用戶所填寫的數(shù)據(jù),并且send(data)到服務(wù)器 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方法里必寫,否則添加數(shù)據(jù)不起作用 request.send(data); request.onreadystatechange=function(){ if(request.readyState===4){//當(dāng)服務(wù)器請(qǐng)求完成 if(request.status===200){//status==200為服務(wù)器請(qǐng)求成功 var data=JSON.parse(request.responseText); if(data.success){//數(shù)據(jù)填寫符合要求 document.getElementById('createResult').innerHTML=data.msg; }else{//數(shù)據(jù)填寫不符合要求 document.getElementById('createResult').innerHTML="出現(xiàn)錯(cuò)誤:"+data.msg; } }else{//服務(wù)器請(qǐng)求失敗 alert("發(fā)生錯(cuò)誤:"+request.status); } } } } } /script body h1員工查詢/h1 label請(qǐng)輸入員工編號(hào):/label input type="text" id="keyword"/ button id="search"查詢/button p id="searchResult"/p h1員工創(chuàng)建/h1 label請(qǐng)輸入員工姓名:/label input type="text" id="staffName"/br label請(qǐng)輸入員工編號(hào):/label input type="text" id="staffNumber"/br label請(qǐng)輸入員工性別:/label select id="staffSex" option男/option option女/option /selectbr label請(qǐng)輸入員工職位:/label input type="text" id="staffJob"/br button id="save"保存/button p id="createResult"/p /body 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

新鄉(xiāng)縣ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!

如何使用JSON連接Android和PHP Mysql數(shù)據(jù)庫(kù)

Android客戶端直接連接遠(yuǎn)程MySQL數(shù)據(jù)庫(kù)的方法如下:String result = ""; //首先使用NameValuePair封裝將要查詢的年數(shù)和關(guān)鍵字綁定 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轉(zhuǎn)化為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通過(guò)JSONArray解析成最終結(jié)果 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開發(fā)中可以直接連接數(shù)據(jù)庫(kù),但是實(shí)際中卻不建議這么做,應(yīng)該使用服務(wù)器端中轉(zhuǎn)下完成。

android怎么得到php發(fā)來(lái)的json數(shù)據(jù)

使用守則

首先,我們要?jiǎng)?chuàng)建Web服務(wù),從MySQL數(shù)據(jù)庫(kù)中讀取數(shù)據(jù)。

?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活動(dòng)讀取Web服務(wù)和解析JSON對(duì)象:

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代碼,將數(shù)據(jù)發(fā)送到Web服務(wù),并將其保存:

?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的活動(dòng),將數(shù)據(jù)發(fā)送到Web服務(wù)作為一個(gè)JSON對(duì)象保存在MySQL數(shù)據(jù)庫(kù)中

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();

}

}

知識(shí)點(diǎn)

要連接到你的模擬器,你可以使用此鏈接:。

要讀取JSON對(duì)象在Web服務(wù)中,您可以使用下面這行代碼:

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

$obj = json_decode($json);


新聞標(biāo)題:安卓phpjson數(shù)據(jù) 安卓php環(huán)境搭建
分享URL:http://weahome.cn/article/ddjdijj.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部