Android中Volley框架Get,POST封装使用及自动解析JSON

  DEMO下载地址:http://download.csdn.net/detail/song2810106/9471616

网络请求使用的Volley.Jar.Json解析使用的谷歌的Gson,此封装可以 重复调用 一个网络请求,并可以自动解析JSON为一个对象,我们都知道,在基本使用Volley的时候,每个Activity 都会去创建一个 网络 请求,这样显得代码很 臃肿 难看。而且有大量的 冗余代码。 VolleyDemo这个类 解决了 在多个Activity 中 调用 这个类 就可以 实现 网络 请求,代码简洁。   

封装采用了 接口回调的方式。 

 首先是 MainActivity 用来实现调用网络请求的 


  volleydemo 是一个封装了Volley请求的单利模式的类,
		

   在MainActivity中 volleyInterface 属于自定义回调接口

 
  
public class MainActivity extends AppCompatActivity {
   
    HashMap map ;
    public static String TAG = "TAG";
    //URL地址
    private String url = "http://api.weidu51.com/v2000/user/login";
    private String url2 = "http://api.weidu51.com/v2000/user/login?account=test1&password=123123";
    private volleyDemo volleydemo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        volleydemo = volleyDemo.getVolleyDemo(MainActivity.this);
        map = new HashMap();
        map.put("account", "test1");
        map.put("password", "123123");
        //发起post请求
        volleydemo.SendVolleyPostBean(url, map, new volleyInterface() {
            @Override
            public void ResponseResult(Object jsonObject) {
                userTestBean userTestBean = (com.demo.binbin.myvolley.com.binbin.volley.userTestBean) jsonObject;
                Log.i("TAG", "POST请求成功" + "姓名:"+userTestBean.getData().getRealname());
            }

            @Override
            public void ResponError(VolleyError volleyError) {
                Log.i("TAG", "POST请求失败" + volleyError.toString());
            }
        }, userTestBean.class);


        volleyInterface volleyInterface = new volleyInterface() {
            @Override
            public void ResponseResult(Object jsonObject) {
                userTestBean userTestBean = (com.demo.binbin.myvolley.com.binbin.volley.userTestBean) jsonObject;
                Log.i("TAG", "GET请求成功" + "姓名:"+userTestBean.getData().getRealname());
            }

            @Override
            public void ResponError(VolleyError volleyError) {
                Log.i("TAG", "GET请求失败" + volleyError.toString());
            }
        };
        //发起get请求
        volleyDemo.getVolleyDemo(MainActivity.this).SendVolleyGetBean(url2, volleyInterface,userTestBean.class);


        volleyDemo.getVolleyDemo(MainActivity.this).SendVolleyGetJsonobject(url2, new volleyInterface() {
            @Override
            public void ResponseResult(Object jsonObject) {
                JSONObject jsonObject1 = (JSONObject)jsonObject;
                Log.i("TAG", "GET请求成功" + "JsonToString"+jsonObject1.toString());
            }

            @Override
            public void ResponError(VolleyError volleyError) {

            }
        }, userTestBean.class);
    }

}
下面的
 
  
volleyInterface 是自定义回调接口
 
  
/**
 * Created by Administrator on 2016-03-08.
 */
public interface volleyInterface {

    void ResponseResult(Object jsonObject);

    void ResponError(VolleyError volleyError);


}
 
  
volleyDemo 类是封装Get,POST的核心类
 
  
/**
 * Created by binbin on 2016-03-08.
 */
public class volleyDemo {
    private  Gson g= new Gson();
    private static RequestQueue requestQueue = null;
    private static volleyDemo volleyDemo;

    public static volleyDemo getVolleyDemo(Context context) {
        if (volleyDemo == null)
            volleyDemo = new volleyDemo();
        requestQueue = Volley.newRequestQueue(context);
        return volleyDemo;
    }
    /**
     * Post请求 url,HashMap,volleyInterface,Class
     * 以实体类形式返回,然后进行强转
     * */
    public void SendVolleyPostBean(String url, HashMap hashMap, final volleyInterface volleyInterface, final Class aClass) {
        Log.i(MainActivity.TAG, "开始请求");

        JSONObject jsonObject = new JSONObject(hashMap);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener() {
            @Override
            public void onResponse(JSONObject jsonObject) {

               Object userBean = (Object) g.fromJson(jsonObject.toString(),aClass);
                volleyInterface.ResponseResult(userBean);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyInterface.ResponError(volleyError);
                Log.i(MainActivity.TAG, "请求错误");
            }
        });

        AddrequestQueue(jsonObjectRequest, true);
    }
    /**
     * GET请求 url,volleyInterface,Class
     * 以实体类形式返回,然后进行强转
     * **/
    public void SendVolleyGetBean(String url, final volleyInterface volleyInterface,final Class aClass) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Object userBean = (Object) g.fromJson(jsonObject.toString(),aClass);
                volleyInterface.ResponseResult(userBean);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyInterface.ResponError(volleyError);
                Log.i(MainActivity.TAG, "请求错误");
            }
        });
        AddrequestQueue(jsonObjectRequest, true);
    }


    /**
     * POST请求 url,volleyInterface,Class
     * 以JSON形式返回,然后进行强转 为JSONobject
     * **/
    public void SendVolleyPostJsonobject(String url, final volleyInterface volleyInterface,final Class aClass) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                volleyInterface.ResponseResult(jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyInterface.ResponError(volleyError);
                Log.i(MainActivity.TAG, "请求错误");
            }
        });
        AddrequestQueue(jsonObjectRequest, true);
    }
    /**
     * GET请求 url,volleyInterface,Class
     * 以JSON形式返回,然后进行强转 为JSONobject
     * **/
    public void SendVolleyGetJsonobject(String url, final volleyInterface volleyInterface,final Class aClass) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                volleyInterface.ResponseResult(jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyInterface.ResponError(volleyError);
                Log.i(MainActivity.TAG, "请求错误");
            }
        });
		加入队列 及设置 请求时间
        AddrequestQueue(jsonObjectRequest, true);
    }
 
  
 
  
	此方法是 Volley配置方法
    public void AddrequestQueue(JsonObjectRequest req, boolean issave) {
        // 设置超时时间
        req.setRetryPolicy(new DefaultRetryPolicy(3 * 1000, 1, 1.0f));
        // 是否开启缓存;
        req.setShouldCache(issave);
        // 将请求加入队列
        requestQueue.add(req);
        // 开始发起请求
        requestQueue.start();
    }




你可能感兴趣的:(android移动开发,Volley封装)