Android Volley的基本用法--StringRequest以及JsonReques

来源:互联网 发布:国家生态系统研究网络 编辑:程序博客网 时间:2024/04/28 02:18

1. Volley简介

volley是android新的网络通信框架,既可以非常简单地进行HTTP通信,也可以轻松加载网络上的图片。除了简单易用之外,Volley在性能方面也进行了大幅度的调整,它的设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常差!

2. 下载Volley

下载链接:
链接:http://pan.baidu.com/s/1eQfJA1O 密码:396r
新建一个Android项目,将volley.jar文件复制到libs目录下!

3. StringRequest的用法

我们就从最基本的HTTP通信开始学习吧,即发起一条HTTP请求,然后接收HTTP响应。首先需要获取到一个RequestQueue对象,可以调用如下方法获取到:

RequestQueue mQueue = Volley.newRequestQueue(context);

发送HTTP请求,创建StringRequest 对象,请求方法有两种:GET和POST

   StringRequest sq = newStringRequest(method, url, listener, errorListener)

   第一个参数是HTTP请求方式,第二个参数就是目标服务器的URL地址,第三个参数是服务器响应成功的回调,第四个参数是服务器响应失败的回调

   第一个参数不写,默认就是使用GET方法

   对于POST方法,StringRequest没有提供设置POST参数的方法,但是当发出POST请求的时候,Volley会尝试调用StringRequest的父类——Request中的getParams()方法来获取POST参数,只需要在StringRequest的匿名类中重写getParams()方法,在这里设置POST参数就可以了。

StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<String, String>();map.put("params1", "value1");map.put("params2", "value2");return map;}};

最后,将这个StringRequest对象添加到RequestQueue

mQueue.add(stringRequest);

4. JsonReques的用法

JsonReques是一个抽象类,要实例它的子类,JsonObjectRequest和JsonArrayRequest。用法跟StringRequest类似:

         JsonObjectRequestr = new JsonObjectRequest(method, url, jsonRequest, listener, errorListener)

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://m.weather.com.cn/data/101010100.html", null,new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.d("TAG", response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e("TAG", error.getMessage(), error);}});

响应的数据就是以JSON格式返回

最后,将这个JsonReques对象添加到RequestQueue

mQueue.add(<span style="font-family: Arial;">jsonObjectRequest</span>);


这两种方法都差不多!






0 0
原创粉丝点击