对于Volley解析框架的原理,背景布过多解释,很多大神都有着详细的介绍。
下面就书写volley的get请求
1.get请求
//获取请求队列
RequestQueue queue = Volley.newRequestQueue(this);
//创建StringRequest
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
//响应成功
@Override
public void onResponse(String s) {
Log.i("xxx", s.toString());
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray data = jsonObject.getJSONArray("data");
if (startNum == 0) {
jsonArray = new JSONArray();
}
for (int i = 0; i < data.length(); i++) {
//把数据源添加到jsonArray
jsonArray.put(data.get(i));
}
initListView(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
//响应错误
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
//把请求方式添加到请求队列
queue.add(request);
}
2.post请求框架
//创建请求队列
RequestQueue queue = Volley.newRequestQueue(this);
//创建请求
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.i("xxx", s.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
//store_id = 3850
map.put("store_id", "3850");
return map;
}
};
//吧请求方式添加到请求队列
queue.add(request);
}