APP端沒有開發(fā)過,但是就像前端一樣,類似 js中的ajax調(diào)用后端接口,只要后端寫好然后json返回正確的格式就好。
創(chuàng)新互聯(lián)建站為您提適合企業(yè)的網(wǎng)站設(shè)計(jì)?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強(qiáng)的網(wǎng)絡(luò)競爭力!結(jié)合企業(yè)自身,進(jìn)行網(wǎng)站設(shè)計(jì)及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作, 我們的網(wǎng)頁設(shè)計(jì)師為您提供的解決方案。
app可以直接發(fā)送http請求給服務(wù)器,然后php程序處理完之后,輸出數(shù)據(jù)到一個(gè)頁面,app獲得這個(gè)頁面就可以解析里面的數(shù)據(jù)。關(guān)于這個(gè)頁面數(shù)據(jù)交換格式有很多成熟的方式,比如 xml,json。
參考:
使用守則
首先,我們要?jiǎng)?chuàng)建Web服務(wù),從MySQL數(shù)據(jù)庫中讀取數(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對象:
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對象保存在MySQL數(shù)據(jù)庫中
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();
}
}
知識點(diǎn)
要連接到你的模擬器,你可以使用此鏈接:。
要讀取JSON對象在Web服務(wù)中,您可以使用下面這行代碼:
$json = file_get_contents('php://input');
$obj = json_decode($json);
根據(jù)你的代碼,你是用的是POST方法。
要在PHP中整體接收POST數(shù)據(jù),有兩種方法。
注意,要使用以下兩種方法,Content-Type不能為multipart/form-data。
方法一:
使用:
file_get_contents('php://input')
其中,php://input是一個(gè)流,可以讀取沒有處理過的POST數(shù)據(jù)(即原始數(shù)據(jù))。相較于$HTTP_RAW_POST_DATA而言,它給內(nèi)存帶來的壓力較小,并且不需要特殊的php.ini設(shè)置。
方法二:
使用此方法,需要設(shè)置php.ini中的always_populate_raw_post_data值為On。
使用$HTTP_RAW_POST_DATA,包含了POST的原始數(shù)據(jù)。但這不是一個(gè)超全局變量,要在函數(shù)中使用它,必須聲明為global,或使用$GLOBALS['HTTP_RAW_POST_DATA']代替。