Volley

作者: lwwlsky | 来源:发表于2016-06-08 15:40 被阅读114次

    Android Volley使用

    Get和Post区别

    • GET用来从服务端获取数据,POST用于上传或者修改数据
    • GET大小限制在2KB以内,POST一般没有限制
    • GET参数在URL,POST参数在请求主体中(也就是用send发送),安全性POST高
    • 部分浏览器会缓存GET请求的response,以至于相同的GET请求会得到相同的response即使服务端的数据已经改变,POST不会被缓存
    • 使用XMLHttpRequest时,POST需要显式指定请求头

    下载Volley的jar包

    git clone https://android.googlesource.com/platform/frameworks/volley

    使用方法

    1. 创建一个RequestQueen对象
    2. 创建一个StringRequest对象
    3. 将StringRequest对象加入RequestQueen中

    `StringRequest stringRequest = new StringRequest (Method.POST, url, listener, errorListener)
    {

    protected Map<String, String> getParams() throws AuthFailureError {  
        Map<String, String> map = new HashMap<String, String>();  
        map.put("params1", "value1");  
        map.put("params2", "value2");  
        return map;  
    }  
    

    };`

    JSONRequest

    jsonRequest是一个抽象类,无法创建实例,JsonRequest有两个子类,
    JsonObjectRequest和JsonArrayRequest,一个是请求一段JSON数据的,一个是用于请求一段JSON数组的

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

    2. JsonObjectRequest对象添加到RequestQueue里
      mQueue.add(jsonObjectRequest);

    这里我们填写的URL地址是http://m.weather.com.cn/data/101010100.html,这是中国天气网提供的一个查询天气信息的接口,响应的数据就是以JSON格式返回的,然后我们在onResponse()方法中将返回的数据打印出来。

    相关文章

      网友评论

          本文标题:Volley

          本文链接:https://www.haomeiwen.com/subject/lgejdttx.html