http://sizeed.blog.163.com/blog/static/965254512012412955872/


如果是PHP做的服务端,要用android去访问,如何办?当然可以用REST,但也可以用点
笨的方法,比如PHP的服务端可以用JSON和XML提供返回的数据,而android端则可以用
APACHE的httpclient去访问.
下面是一个例子,假设数据表中users表有如下字段(mysql):
idusers,UserName,FullName,加点数据.然后在服务端PHP,建立一个
webservice1.php,作用是直接返回服务端数据库的数据,如下:
Java代码
<?php
if(isset($_GET['user']) && intval($_GET['user'])) {


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

/* 连接数据库*/
$link = mysql_connect('localhost','root','xxxxx') or die('Cannot connect to the DB');
mysql_select_db('jsonandroid',$link) or die('Cannot select the DB');

$query = "SELECT * FROM `users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}

/* json格式*/
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '<posts>';
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 '</posts>';
}

}
?>

<?php
if(isset($_GET['user']) && intval($_GET['user'])) {


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

/* 连接数据库*/
$link = mysql_connect('localhost','root','xxxxx') or die('Cannot connect to the DB');
mysql_select_db('jsonandroid',$link) or die('Cannot select the DB');

$query = "SELECT * FROM `users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}

/* json格式*/
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '<posts>';
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 '</posts>';
}

}
?>

则可以把数据表输出为JSON或者XML格式了.客户端的ANDROID调用:
Java代码

try {

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpParams p = new BasicHttpParams();

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


HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);


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

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// 解析JSON返回的 JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, 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();


try {

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpParams p = new BasicHttpParams();

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


HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);


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

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// 解析JSON返回的JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, 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();


再搞个webservice2.php,该文件用来把客户端传送过去的JSON数据保存
Java代码

<?php

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

//echo $json;


//保存数据库
$con = mysql_connect('localhost','root','XXX') or die('Cannot connect to the DB');
mysql_select_db('jsonandroid',$con);

mysql_query("INSERT INTO `users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");

mysql_close($con);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));

?>


<?php

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

//echo $json;


//保存数据库
$con = mysql_connect('localhost','root','XXX') or die('Cannot connect to the DB');
mysql_select_db('jsonandroid',$con);

mysql_query("INSERT INTO `users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");

mysql_close($con);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));

?>


而ANDROID端的,可以构造JSON,发送到webservice2.php

Java代码
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 = "http://10.0.2.2:8082//myphp/phpWebservice/webservice2.php";

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

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 = "http://10.0.2.2:8082//myphp/phpWebservice/webservice2.php";

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

这样,就可以把ANDROID发送的数据保存到服务端了


更多相关文章

  1. android登录模块之静态登录
  2. Android(安卓)实现歌词同步
  3. Android(安卓)音视频深入 四 Android原生API录视频MP4,有缺陷,没有
  4. Android(安卓)MVP 模式:简单易懂的介绍方式
  5. android TextView显示文字和图片
  6. android开发――获取手机联系人
  7. Android使用Google Breakpad进行崩溃日志管理
  8. 阿里路由框架ARouter简介
  9. android 玩转ContentProvider之三--实现一个ContentProvider对多张

随机推荐

  1. Android在代码中开启OpenGL 4xMSAA 抗锯
  2. Node.js与Android(安卓)SDK的下载与部署
  3. 【10.2移动新特性】好用的Application Fr
  4. Android中的FlexboxLayout
  5. Android中MenuInflater实例
  6. android app 不会被low memory killer回
  7. 在配置最新Androi adt20.0.0 遇到的一些
  8. CSS3实现android(安卓)Logo图标效果
  9. Qt 实现android camera摄像头的preview和
  10. android检测网络是否正常