android使用json与php服务端通信总结

android使用json与php服务端通信总结


android客户端通过get,post进行数据交互

【get方式】
protected String getRequest(String url, DefaultHttpClient client) throws Exception {
DefaultHttpClient client = new DefaultHttpClient(new BasicHttpParams());
//超时请求
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
//读取超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

String result = null;
int statusCode = 0;
HttpGet getMethod = new HttpGet(url);

try {
//读取超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

HttpResponse httpResponse = client.execute(getMethod);
//statusCode == 200 正常
statusCode = httpResponse.getStatusLine().getStatusCode();

//处理返回的httpResponse信息
result = retrieveInputStream(httpResponse.getEntity());
} catch (Exception e) {

} finally {
getMethod.abort();
}
return result;
}

/**
* 处理httpResponse信息,返回String
*
* @param httpEntity
* @return String
*/
protected String retrieveInputStream(HttpEntity httpEntity) {
Long l = httpEntity.getContentLength();
int length = (int) httpEntity.getContentLength();
//the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
//length==-1,下面这句报错,println needs a message
//System.out.println("length = "+length);
if (length < 0) length = 10000;
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
}catch(IOException e){
e.printStackTrace();
}
return stringBuffer.toString();
}


【post方式】

//////
List nameValuePairs = new List();//构建post给php的参数
nameValuePairs.add(new BasicNameValuePair("key","value"));

//通过post获得数据
public static String postHttpData(String url,List nameValuePairs)
{
String resultStr=null;
HttpClient httpclient = new DefaultHttpClient();
//超时请求
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
//读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response=httpclient.execute(httppost);
resultStr=retrieveInputStream(httpResponse.get

Entity());
} catch (UnsupportedEncodingException e) {
Log.d(url, "UnsupportedEncodingException");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d(url, "ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
Log.d(url, "IOException");
e.printStackTrace();
}
return resultStr;
}

get的参数设置是有长度限制的,在用json传递大数据量时,get方式很可能超过长度。
post的参数没有长度限制,可以放心使用。
注意超时的部分,网络不稳定或是其他情况,可是非常有必要的,
不然android客户端卡住就影响用户体验了。


===========================================

php服务端构造json数据

json和XML一样也是国际通用标准的,以字符串的形式展示.
php有自带的库函数,可以方便的在php对象和json对象之间转换。

php转为json 编码: $json_string = json_encode($php_obj);
json转为php 解码: $php_obj = json_decode($json_string);

根据数据的复杂度,灵活编码使用:
普通对象:
$success_arr = array(
'code'=>$SUCCESS_CODE,
'data'=>array(
'result'=>'true',
'points'=>100,
'desc'=>'some string data'
));


数组对象:
$fields = array();

foreach($reslist as $resitem){
$fields[] = array(
'name'=>$resitem->name,
'content'=>$resitem->content,
'image_url'=>$resitem->image_url);

}

$json = json_encode($fields);//这里的$json值为数组对象
$result = '{"simple":' . $json . '}';//或者组装成带个对象


解码为反向过程,不再多述。


===========================================

json数据格式解析

可以分为三种形式:
1.普通形式
2.数组形式
3.混合形式-对象中带有数组

【普通形式的】
服务器端返回的json数据格式如下:
{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

简单json的数据格式表示单个抽象对象,以"{"开始,"}"结束。
每一个键值对通过":"组装,前后分别是key和value,类似ini文件,
但是因为"{}","[]"的配合使用,比ini文件格式要优,能够简单的清晰的描述复杂抽象对象。

[有人说XML也可以清晰描述啊,是的,没错。
但是XML使用了很多标签,对于网络通信来说,越少数据传输,就省时省流量。
而如果移动设备,省流量省时,就等于是省电!扯远了~]

以上表示一个userbean,有uid,showname,avtar,state属性,以及各个属性的值。

在android中,可以方便的转换json对象,
JSONObject jsonObject = new JSONObject(json_string);//json_string就是上面的字符串了
JSONObject ub = jsonObject.getJSONObject("userbean");//得到userbean对象

String Uid = json

Object.getString("Uid");
String Showname = jsonObject.getString("Showname");
String Avtar = jsonObject.getString("Avtar");
String State = jsonObject.getString("State");


【混合形式-对象中带有数组(数组和混合形式一起总结)】
服务器端返回的数据格式如下:
{"calendar":
{"calendarlist":
[
{"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
{"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
]
}
}

数组,即有多个同类对象,解析如下:
JSONObject jsonObject = new JSONObject(json_string);//json_string就是上面的字符串了
JSONObject ub = jsonObject.getJSONObject("calendar");//得到calendar对象

//得到calendarlist列表,即[]中的内容.
//如果服务器只返回数组部分json,则直接使用getJSONArray,即数组形式
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for(int i=0;iJSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
jsonObject2.getString("calendar_id");
jsonObject2.getString("title");
jsonObject2.getString("category_name");
jsonObject2.getString("showtime");
jsonObject2.getString("endshowtime");
jsonObject2.getBoolean("allDay");
}

【总结】
普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。

【基础学习】
json基础请查看网址:https://www.360docs.net/doc/e0801072.html,/softwaredevelop/archive/2010/04/07/1706494.html


相关文档
最新文档