zoukankan      html  css  js  c++  java
  • volley

    一、StringRequest的用法

    发起一条HTTP请求,然后接受HTTp响应:GET

    1.创建一个RequestQueue对象,他是一个请求列对象,可以缓存所有的http请求,然后按照一定的算法并发的发出这些请求。

    2.创建一个StringRequest对象

    3.将StringRequest对象添加到RequestQueue里面。

    首先需要获取到一个RequestQueue对象

    RequestQueue mQueue=Volley.newRequestQueue(context);

    这里的RequestQueue是一个请求队列对象,他可以缓存所有的HTTP请求,,然后按照一定的算法并发的发出这些请求。

    接下来为了要发出一条HTTP请求,还需要创建一个StringRequest对象:

    StringRequest stringRequest=new StringRequest("http://www.baidu.com",new Response.Listener<String>(){
    
        @Override
    
        public void onResponse(String response){
            Log.d("TAG",response);}
            //对数据的解析从这里面操作
    
        },new Response.ErrorListener(){
    
            @Override
    
            public void onErrorResponse(VolleyError error){
    
            Log.e("TAG",error.getMessage(),error);
        }
    });

    可以看到,这里new出一个StringRequest对象,StringRequest的构造函数需要传入三个参数,第一个参数是目标服务器的URL地址,第二个参数是服务器响应成功的回调,第三个参数是服务器响应失败的回调。其中,在响应成功的回调里打印出服务器返回的内容,可对返回的数据进行操作,在相应失败的回调里打印失败的详细信息。

    最后,将这个StringRequest对象添加到RequestQueue里面就可以了,如下:

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
    15000, //默认超时时间
    0, //默认最大尝试次数 
    1f));
    stringRequest.setShouldCache(false);//设置不缓存数据
    mQueue.add(stringRequest);

    另外,由于Volley要访问网络,应在AndroidManifest.xml添加如下权限:

    <uses-permission android:name="android.permission.INTERNET" /> 

    HTTP的请求类型通常有两种,GET和POST,刚才是GET请求

    StringRequest中还提供了另外一种四个参数的构造函数,第一个参数时指定请求类型的:

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

    当发出POST请求的时候,Volley会尝试调用StringRequest的父类——Request中的getParams()方法来获取POST参数,我们只需要在StringRequest的匿名类中重写getParams()方法,在这里设置POST参数:

    StringRequest stringRequest =new StringRequest(Method.POST,url,listener,errorListener){
    //这里的url值得是目标网址?之前的数据,getParams中的是键值对,对应?后面的数据
    
    @Override
    
    protected Map<String,String> getParams() throws AuthFailureError{
    
    Map<String,String> map=new HashMap<String,String>();
    
    map.put("paras1","value1");
    
    map.put("paras1","value1");
    
    return map;}
    
    };

    二、JsonRequest的用法

    JsonRequest也是继承自Request类,不过由于JsonRequest是一个抽象类,因此无法直接创建他的实例,只能从他的子类入手,JsonRequest有两个直接的子类,JsonObjectRequest(请求一段JSON数据)JsonArrayRequest(请求一段JSON数组),他们的用法基本上也没什么特别之处:

    JsonObjectRequest jsonObjectRequest=new JsonBbjectRequest("http://www.baidu.com,null,
    
    new Response.Listener<JSONObject>(){
    
    @Override
    
    public void onResponse(JSONObject response){
    
    Log.d("TAG",response.toString());}
    
    },new Response.ErroListener(){
    
    @Override
    
    public void onErrorResponse(VolleyError error ){
    
    Log.e("TAG",error.getMessage(),error);}
    
    });
    
    mQueue.add(jsonObjectRequest);
    private void request() {
    
            loadList = new WDialog(getActivity(), R.layout.custom_dialog,
                    R.style.dialogStyle);
            loadList.setCanceledOnTouchOutside(false);
            loadList.show();
    
            String url = WR.URL;
    
            StringRequest stringRequest = new StringRequest(Method.POST, url,
                    new Response.Listener<String>() {
    
                        @Override
                        public void onResponse(String response) {
    
                            try {
                                JSONObject obj = new JSONObject(response);
                                String nosString = obj.optString("no");
    
                                if (nosString.equals("1")) {
    
                                    try {
                                        JSONArray jsonArray = new JSONObject(response)
                                        .getJSONArray("obj");
    
                                        if (null != jsonArray) {
    
                                            list.clear();
                                        }
                                        for (int i = 0; i < jsonArray.length(); i++) {
    
                                            JSONObject jsonValue = jsonArray
                                                    .getJSONObject(i);
    
                                            Mzgz sm = new Mzgz();
                                            sm.setPhbm(jsonValue.optString("phbm", ""));
                                            sm.setCyry(jsonValue.optString("cyry", ""));
                                            list.add(sm);
                                        }
                                        adapter.notifyDataSetChanged();
                                        loadList.dismiss();
    
                                    } catch (Exception e) {
    
                                        adapter.clear();
                                        loadList.dismiss();
                                        UIUtil.networkToast(getActivity(),
                                                WR.W_NOT_DATA);
                                    }
    
                                } else {
    
                                    loadList.dismiss();
                                    UIUtil.networkToast(getActivity(),
                                            WR.W_NOT_DATA);
                                }
    
                            } catch (Exception e) {
    
                                loadList.dismiss();
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
    
                        @Override
                        public void onErrorResponse(VolleyError error) {
    
                            loadList.dismiss();
                            UIUtil.networkToast(getActivity(), WR.W_HTTP_ERROR);
                            Log.e("TAG", error.getMessage(), error);
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
    
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("key1", key1);
                    params.put("key2", key2);return params;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 0, 1f));
            stringRequest.setShouldCache(false);
            mQueue.add(stringRequest);
        }
  • 相关阅读:
    ES 遇到 unassigned shard如何处理?
    elasticsearch如何安全重启
    Agg学习笔记
    二进制文件中读写结构体
    C语言 结构体数组保存到二进制文件中
    Memcache 笔记
    memcached完全剖析–1. memcached的基础
    Redis和Memcache对比及选择
    Exploring the MapBox stack: MBTiles, TileJSON, UTFGrids and Wax
    Tilemill + tilestream + mapbox.js 自制地图
  • 原文地址:https://www.cnblogs.com/chhom/p/4791383.html
Copyright © 2011-2022 走看看