Android之网络通信Volley框架用法

概述:

Volley提供的功能

简单的讲,提供了如下主要的功能:

1、封装了的异步的RESTful 请求API;

2、一个优雅和稳健的请求队列;

3、一个可扩展的架构,它使开发人员能够实现自定义的请求和响应处理机制;

4、能够使用外部HTTP Client库;

5、缓存策略;

6、自定义的网络图像加载视图(NetworkImageView,ImageLoader等);

Volley也有两种加载方式DoGet和DoPost。

代码:

将volley框架单例封装成一个方法:

/** * Created by Administrator on 2015/9/14. * 单例模式的RequestQueue,可以防止内存溢出 */{private static MySingleTon mInstance;private RequestQueue mRequestQueue;private static Context mCtx;private MySingleTon(Context context) {mCtx = context;mRequestQueue = getRequestQueue();}MySingleTon getInstance(Context context) {if (mInstance == null) {mInstance = new MySingleTon(context);}return mInstance;}public RequestQueue getRequestQueue() {if (mRequestQueue == null) {// getApplicationContext() is key, it keeps you from leaking the// Activity or BroadcastReceiver if someone passes one in.mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());}return mRequestQueue;}public <T> void addToRequestQueue(Request<T> req) {getRequestQueue().add(req);}}

DoGet方式:

() {//RequestQueue queue = Volley.newRequestQueue(getApplicationContext());//response的监听有两种,,一个是正确响应的监听,一个是错误响应的监听,当没有网络时,网络连接会出错StringRequest request = new StringRequest(Request.Method.GET, “http://www.360.com”, new Response.Listener<String>() {(String response) {mTextViewContent.setText(response);}}, new Response.ErrorListener() {(VolleyError error) {mTextViewContent.setText(“网络连接错误!”);}});MySingleTon.getInstance(getApplicationContext()).addToRequestQueue(request);}

DoPost方式:

() {//RequestQueue queue = Volley.newRequestQueue(getApplicationContext());StringRequest request = new StringRequest(Request.Method.POST, “http://192.168.0.30:8080/MyWebTest/MyTestServerlet”, new Response.Listener<String>() {(String response) {mTextViewContent.setText(response);}}, new Response.ErrorListener() {(VolleyError error) {mTextViewContent.setText(“网络连接错误!”);}}){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {HashMap<String,String> map = new HashMap<>();map.put(“username”,”zhaoliu”);return map;}};MySingleTon.getInstance(getApplicationContext()).addToRequestQueue(request);}

结果演示:

销售世界上第一号的产品–不是汽车,而是自己。

Android之网络通信Volley框架用法

相关文章:

你感兴趣的文章:

标签云: