AsyncHttpClient 網路請求+ fastJson解析資料
阿新 • • 發佈:2019-02-15
1.首先需要在程式碼中新增這兩個控制元件的jar包支援:
厚顏無恥附上下載連結:
http://download.csdn.net/download/sk2die/10153192
2.使用get請求獲取伺服器資料(json)
注意:json解析時應判斷json資料格式是否正確書寫,否則容易出錯。
json資料格式:
{
"imageArr": [
{
"ID": "1",
"IMAPAURL": "http:// ******** ",
"IMAURL": "http:// ********"
},
{
"ID" : "2",
"http:// ********",
"IMAURL": "http:// ********"
},
{
"ID": "3",
"IMAPAURL": "http:// ********",
"IMAURL": "http:// ********"
},
{
"ID": "5",
"IMAPAURL": "http:http:// ********",
"IMAURL" : "http:// ********"
}
],
"proInfo": {
"id": "1",
"memberNum": "100",
"minMoney": "100",
"money": "10",
}
}
對應的類如下(相應的Image和product又是一個類,這裡就不相應貼出,原理相同):
public class Index {
public Product product;
public List<Image> imageList;
}
AsyncHttpClient client = new AsyncHttpClient();
client.get("這裡應放上面的json資料的url地址", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, String content) {
index = new Index();
JSONObject jsonObject = JSON.parseObject(content);
String imageArr = jsonObject.getString("imageArr");
List<Image> images = JSON.parseArray(imageArr, Image.class);
String proInfo = jsonObject.getString("proInfo");
Product product = JSON.parseObject(proInfo, Product.class);
index.product = product;
index.imageList = images;
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
});
如此,json解析之後index物件中就存放了前面json資料格式中的全部資料,可以通過點屬性(如index.product.id)的方式獲取。
3.利用post請求向伺服器傳遞json陣列:
下面是json陣列的封裝:
下面的object僅有兩個屬性,id和answer。個數為mapSize個。
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < mapSize; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", i);
jsonObject.put("answer", et[i].getText().toString());
jsonArray.add(jsonObject);
}
AsyncHttpClient的處理部分
AsyncHttpClient client = new AsyncHttpClient();
String url = AppHttpUrl.url;
client.addHeader("cookie", Util.getSessionId());//新增cookie,表示請求頭。
RequestParams params = new RequestParams();
params.put("ans",jsonArray.toString());
client.post(getApplicationContext(), url,params,new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, String content) {
super.onSuccess(statusCode, content);
JSONObject jsonObject = JSON.parseObject(content);
if (jsonObject != null) {
if (jsonObject.getInteger("success") == 0) {
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
AppManager.getInstance().removeAll();
}
}
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
});
將session儲存到SharedPreferences中
Headers headers = response.headers();
List<String> cookies = headers.values("Set-Cookie");
if (cookies.size() > 0) {
String session = cookies.get(0);
String s = session.substring(0, session.indexOf(";"));
Util.setPhpSessionId(s);
}