Volley入门

谷歌2013年推出的一款网络请求框架Volley   而且听说httpclient废弃了已经

特点:通信更快,更简单

    get,post网络请求及网络图像的高效异步处理请求,可以对网络请求进行排序以及优先级处理

    网络请求的缓存

    多级别取消请求

    和Activity生命周期的联动:当Activity被销毁可以取消停止网络请求

缺点:不适合数据的上传和下载

为什么使用Volley

功能上:

高校的Get/Post方式的数据请求交互

网络图片加载和缓存

其他:谷歌官方推出,性能和稳定和强劲

下面进入实战练习

Android Volley框架的使用:

知识点有:

Volley的get和post请求方式的使用

Volley的网络请求队列建立和取消队列请求

Volley与Activity生命周期的联动

Volley的简单的二次回调封装

1.理论课堂:

一Volley的get和poset请求方式的使用

Get和Post请求接口数据的使用

挑选合适的对象:

StringRequest//对返回的数据类型不确定时使用

JsonObjectRequest//确定返回对象是JsonObject类型时调用

JsonArrayRequest//确定返回对象是JsonArrayRequest类型时调用

回调的使用:请求成功,请求失败等情况的方法回调

Volley的网络请求队列的建立和取消队列请求:

在使用Volley时需要建立一个全局请求队列,然后再建立一个请求,并加入到全局队列。方便对请求的管理

Volley与Activity生命周期的联动

特点:可以在Activity销毁的时候,同时关闭请求

关键点:

设置Tag标签,在Activity 的onStop方法中根据Tag标签查找取消请求

Volley的简单的二次回调封装:使用自定义的,创建一个全局的,方便管理

案例一:get,Post请求:

第一步建立全局请求队列:

package com.example.volley;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import android.app.Application;

public class MyApplication extends Application{
	/*
	 * 建立全局队列
	 */
	public static RequestQueue queues;
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		queues = Volley.newRequestQueue(getApplicationContext());

	}
	public static RequestQueue getHttpRequestQueues(){
		return queues;
	}
}

不要忘了在配置文件中注册Application,和网络权限

使用get请求:

package com.example.volley;

import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		volley_Get();
	}

	private void volley_Get() {
		// TODO Auto-generated method stub
		String url = "http://wthrcdn.etouch.cn/weather_mini?city=开封";
		//参数依次代表意思:请求方法,请求地址,请求成功回调监听,请求失败回调监听
		StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), response, 1).show();
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		});
		request.setTag("mytag");//给请求设置标签,方便加入队列后查找
		MyApplication.getHttpRequestQueues().add(request);//添加到请求队列

		//如果已经知道返回值类型比如JsonObject可以直接使用JsonObject类型提高解析效率
		//第三个参数请求的数据传递,因为是get请求,数据包含在url中了,这里传null就行,如果是post请求,第三个参数是传递数据
		//		JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
		//
		//			@Override
		//			public void onResponse(JSONObject response) {
		//				// TODO Auto-generated method stub
		//				Toast.makeText(getApplicationContext(),response.toString() , 0).show();
		//			}
		//		}, new Response.ErrorListener(){
		//
		//			@Override
		//			public void onErrorResponse(VolleyError error) {
		//				// TODO Auto-generated method stub
		//
		//			}
		//
		//		});
		//		mJsonObjectRequest.setTag("mytag");//给请求设置标签,方便加入队列后查找
		//		MyApplication.getHttpRequestQueues().add(mJsonObjectRequest);//添加到请求队列

	}
}

使用post请求:

private void volley_Post() {
		// TODO Auto-generated method stub
		String url = "http://wthrcdn.etouch.cn/weather_mini?";
		//参数依次代表意思:请求方法,请求地址,请求成功回调监听,请求失败回调监听
		//		StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() {
		//
		//			@Override
		//			public void onResponse(String response) {
		//				// TODO Auto-generated method stub
		//				Toast.makeText(getApplicationContext(), response, 1).show();
		//			}
		//		}, new Response.ErrorListener() {
		//
		//			@Override
		//			public void onErrorResponse(VolleyError error) {
		//				// TODO Auto-generated method stub
		//				Toast.makeText(getApplicationContext(), error.toString(), 1).show();
		//			}
		//		}){
		//			//使用post需要实现专门传递参数的方法
		//			@Override
		//			protected Map<String, String> getParams() throws AuthFailureError {
		//				// TODO Auto-generated method stub
		//				Map<String, String> hashMap = new HashMap<String, String>();
		//				hashMap.put("city", "开封");
		//				return hashMap;
		//			}
		//		};
		//		request.setTag("mytag");//给请求设置标签,方便加入队列后查找
		//		MyApplication.getHttpRequestQueues().add(request);//添加到请求队列


		//如果已经知道返回值类型比如JsonObject可以直接使用JsonObject类型提高解析效率
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("city", "开封");
		JSONObject object = new JSONObject(map);//将map转换为JsonObject类型

		JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Method.GET, url, object, new Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),response.toString() , 0).show();
			}
		}, new Response.ErrorListener(){

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}

		});
		mJsonObjectRequest.setTag("mytag");//给请求设置标签,方便加入队列后查找
		MyApplication.getHttpRequestQueues().add(mJsonObjectRequest);//添加到请求队列



	}

实现与Activity的联动:

@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//实现与Activity的联动,当Activity停止的时候停止请求
		MyApplication.getHttpRequestQueues().cancelAll("mytag");//通过给定的tag值,将指定的队列全部关闭
	}

get,post请求回调的二次封装


package com.example.volley;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

import android.content.Context;

public abstract class VolleyInterface {
	public Context mContext;
	public static Listener<String> mListener;
	public static ErrorListener mErrorLiseListener;
	public VolleyInterface(Context context,Listener<String> listener,ErrorListener errorListener){
		this.mContext = context;
		this.mErrorLiseListener = errorListener;
		this.mListener = listener;
	}
	public abstract void onMySuccess(String result);
	public abstract void onMyError(VolleyError error);

	public Listener<String> loadingListener(){
		mListener = new Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				//弹出正在加载
				onMySuccess(response);//回调抽象类
			}
		};
		return mListener;
	}

	public ErrorListener errorListener(){
		mErrorLiseListener = new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub
				//弹出请求失败
				onMyError(error);
			}
		};
		return mErrorLiseListener;
	}
}

package com.example.volley;

import java.util.Map;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;

public class VolleyRequest {
	/**
	 * 对Volley请求回调进行二次封装,方便使用
	 * 这里以StringRequest为例
	 */
	public static StringRequest stringRequest;
	public static Context context;

	public static void RequestGet(Context mContext,String url,String tag,VolleyInterface vif){
		MyApplication.getHttpRequestQueues().cancelAll(tag);//在请求之前把之前的请求取消,放在进行重复的请求消耗内存
		stringRequest = new StringRequest(Method.GET, url, vif.loadingListener(), vif.errorListener());
		stringRequest.setTag(tag);
		MyApplication.getHttpRequestQueues().add(stringRequest);
		MyApplication.getHttpRequestQueues().start();

	}
	public static void RequestPost(Context mContext,String url,String tag,
			final Map<String, String> params ,VolleyInterface vif){
		MyApplication.getHttpRequestQueues().cancelAll(tag);
		stringRequest = new StringRequest(Method.POST,url, vif.loadingListener(), vif.errorListener()){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				return params;
			}
		};
		stringRequest.setTag(tag);
		MyApplication.getHttpRequestQueues().add(stringRequest);
		MyApplication.getHttpRequestQueues().start();

	}

}
使用:

private void volley_myGet() {
		// TODO Auto-generated method stub
		String url = "http://wthrcdn.etouch.cn/weather_mini?city=开封";
		VolleyRequest.RequestGet(this, url, "mytag", new VolleyInterface(this,VolleyInterface.mListener,VolleyInterface.mErrorLiseListener) {

			@Override
			public void onMySuccess(String result) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), result, 0).show();
			}

			@Override
			public void onMyError(VolleyError error) {
				// TODO Auto-generated method stub

			}
		});
	}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值