大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
APP端没有开发过,但是就像前端一样,类似 js中的ajax调用后端接口,只要后端写好然后json返回正确的格式就好。
创新互联建站为您提适合企业的网站设计 让您的网站在搜索引擎具有高度排名,让您的网站具备超强的网络竞争力!结合企业自身,进行网站设计及把握,最后结合企业文化和具体宗旨等,才能创作出一份性化解决方案。从网站策划到成都网站设计、成都网站制作, 我们的网页设计师为您提供的解决方案。
app可以直接发送http请求给服务器,然后php程序处理完之后,输出数据到一个页面,app获得这个页面就可以解析里面的数据。关于这个页面数据交换格式有很多成熟的方式,比如 xml,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);
根据你的代码,你是用的是POST方法。
要在PHP中整体接收POST数据,有两种方法。
注意,要使用以下两种方法,Content-Type不能为multipart/form-data。
方法一:
使用:
file_get_contents('php://input')
其中,php://input是一个流,可以读取没有处理过的POST数据(即原始数据)。相较于$HTTP_RAW_POST_DATA而言,它给内存带来的压力较小,并且不需要特殊的php.ini设置。
方法二:
使用此方法,需要设置php.ini中的always_populate_raw_post_data值为On。
使用$HTTP_RAW_POST_DATA,包含了POST的原始数据。但这不是一个超全局变量,要在函数中使用它,必须声明为global,或使用$GLOBALS['HTTP_RAW_POST_DATA']代替。