上一篇文章介绍了Volley框架的来源,特点。以及StringRequest类的使用。如果你没有阅读过浅谈网络框架Volley(一),建议看一下之后再看这篇文章。
这篇文章给大家继续分享Volley的其他两个请求对象,JsonObjectRequest和JsonArrayRequest对象,这两个对象的父类是JsonRequest对象,但是JsonRequest是抽象类,我们只能使用他的两个子类。我还是带着大家看一遍体系结构,这样看过之后,使用起来就简单了。下面是简易的体系图。
abstract class Request
|
| extends↑
|
abstract class JsonRequest class StringRequest
|
| extends↑
|
class JsonObjectRequest
class JsonArrayRequest
你可以从JsonRequest抽象类中看到,并没有定义什么核心方法,那我们直接就看一下JsonObjectRequest类,发现构造函数有重载有两个构造函数
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
//===========================================
public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
我相信你看一眼就懂了,第一个构造函数是让你指定请求方式。第二个构造函数是看你有没有传参JsonObject,如果没有就是Get请求,如果有就是Post,接下来我就用第二个构造函数创建对象的方式演示一下Get
RequestQueue queues = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest request = new JsonObjectRequest("http://www.baidu.com", null, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
queues.add(request);
结果你一定想不到,竟然调用了请求失败的回调函数。这是为什么呢?是因为http://www.baidu.com返回的是html,也就是一堆String。顾名思义,JsonObjectRequest是用来请求返回的是Json数据的,这个地址返回的是String,当然报错!,你换一个响应结果是Json的就可以了
以后要是明确返回结果是Json就选用JsonRequest的两个子类请求,如果不明确结果就用StringRequest,但是相比效率下,StringRequest包含了JsonObject两个子类对象的特性,所以说开发中还是要选择合适的对象使用
下面是Post请求,也是非常简单了。这种没有技术含量的东东,看一遍打一遍就会了!
//创建一个Map集合,并添加参数
Map<String, String> hashMap = new HashMap<>();
hashMap.put("key","&q=%E6%99%AE%E4%BA%AC%E5%A4%B1%E8%B8%AA");
//创建JsonObject对象,利用构造函数将Map集合加入
JSONObject object = new JSONObject(hashMap);
//一往如前
RequestQueue queues = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest request = new JsonObjectRequest("http://op.juhe.cn/onebox/news/query", object, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
queues.add(request);
这样的话,JsonRequest的子类JsonObjectRequest也弄完了,还剩一个JsonArrayRequest,那么下面再说一下JsonArrayRequest对象的使用?想得美。。举一反三,自己看一下得了!那这篇文章就写到这里!下一篇文章会介绍与图片打交道!