【Volley网络框架】的简单使用

时间:2023-02-11 21:54:22

先来介绍一下Volley网络框架使用的流程:

1、Volley进行网络请求统一管理,RequestQueue
2、发起请求,StringRequest(分为GET,POST请求 后面会一一介绍),ImageRequest,JSONObjectRequest
3、将请求添加到请求队列

【Volley网络框架】的简单使用

此Demo中所用到的网络请求!(只是几个简单的Button,就不往出列xml文件了...)

1.get请求获取数据:

case R.id.btnGetString:
String stringUrl = "http://www.baidu.com";
request = new StringRequest(
Request.Method.GET,//请求方式
stringUrl,//地址
new Response.Listener<String>() {//请求成功回调
@Override
public void onResponse(String response) {
//对数据进行解析,刷新适配器,展示数据
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: Get请求获取的数据: " + response);
}
},
new Response.ErrorListener() {//请求失败的回调
@Override
public void onErrorResponse(VolleyError error) {
//网络不好,提示用户,从缓存中获取数据
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onErrorResponse: Get请求失败: " + error.getMessage());
}
});
break;

2.post请求获取数据:

case R.id.btnPostString:
request = new StringRequest(Request.Method.POST,
mStringPostUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject result = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: POST请求获取数据: " + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onErrorResponse: POST请求失败:" + error.getMessage());
//断网的情况下获取数据 String类型数据(Json)
//从缓存中获取数据
Cache cache = mRequestQueue.getCache();
if (cache != null) {
Cache.Entry entry = cache.get(mStringPostUrl);
if (entry != null) {
byte[] data = entry.data;
String result = new String(data);
//TODO JSON解析,刷新适配器,ListView展示数据
Log.d("flag", "----------------->onErrorResponse: 断网下获取的缓存数据: " + result);

}
}
}
}) {//重写StringRequest的方法
//Ctrl+O
//params---->参数,请求参数:cateid=0;p = 1;
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("catied", "0");
map.put("p", "1");
return map;
}
};
break;

3.图片的请求

case R.id.btnImage:
request = new ImageRequest(mImageUrl,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
mImageView.setImageBitmap(response);
Log.d("flag", "----------------->onResponse: 图片的尺寸, width: "
+ response.getWidth() + ",height: " + response.getHeight());
}
},
//图片的缩放,压缩
300,//宽度的最大值,0,不进行缩放
400, //高度的最大值,0,不进行缩放
ImageView.ScaleType.FIT_XY,
Bitmap.Config.RGB_565, //Bitmap生成的配置格式
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
mImageView.setImageResource(R.mipmap.ic_launcher);
Log.d("flag", "----------------->onErrorResponse: 图片获取失败 " + error.getMessage());
}
});
break;

4.从缓存中获取图片

case R.id.btnCache://获取PostString

//1、通过请求队列获取缓存
Cache cache = mRequestQueue.getCache();
if (cache != null) {
Cache.Entry entry = cache.get(mImageUrl);
if (entry != null) {
//获取entry中数据
byte[] data = entry.data;
// String result = new String(data);
// result = data.toString();内存地址
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
// Log.d("flag", "----------------->volley: 缓存中数据: " + result);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mImageView.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "具体的网址没有缓存数据", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "没有缓存对象", Toast.LENGTH_SHORT).show();
}
break;

5.post请求方式 获取字符串

case R.id.btnJson:

String jsonUrl = "http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api";
JSONObject params = new JSONObject();

try {
params.put("locationId", "290");
} catch (JSONException e) {
e.printStackTrace();
}
request = new JsonObjectRequest(Request.Method.POST,
jsonUrl,
params,//如果是GET请求,null
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//TODO 直接进行解析,方便操作
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: 获取的JSON数据是: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("flag", "----------------->onErrorResponse: " + error.getMessage());
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
break;

6.获取缓存中的图片

case R.id.btnImageLoader:
//参数二,内存缓存 运行内存
ImageLoader imageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
//内存缓存LruCache链表
LruCache<String, Bitmap> lruCache =
new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
@Override
protected int sizeOf(String key, Bitmap value) {
// value.getRowBytes()*value.getHeight();
return value.getByteCount();//
}
};

@Override
public Bitmap getBitmap(String url) {
return lruCache.get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
lruCache.put(url, bitmap);
}
});
imageLoader.get(mImageUrl, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response,
boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
mImageView.setImageBitmap(bitmap);
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "请求图片失败", Toast.LENGTH_SHORT).show();
}
}, 256, 360, ImageView.ScaleType.CENTER_CROP);
break;

最重要的一行代码:

if (request != null) {
mRequestQueue.add(request);
}

下面的是一些是 自定义的RequestQueue和ImageLoader

(如果不想修改缓存的位置可以跳过)

1.自定义的VolleyUtils

public class VolleyUtils {

//线程安全--->恶汉式
private static VolleyUtils ourInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

public RequestQueue getRequestQueue() {
return mRequestQueue;
}

public ImageLoader getImageLoader() {
return mImageLoader;
}

//公有访问方法
public static VolleyUtils getInstance(Context context) {

if (ourInstance == null) {//线程不安全的问题
synchronized (VolleyUtils.class) {
if (ourInstance == null) {
ourInstance = new VolleyUtils(context);
}
}
}
return ourInstance;
}

//私有的构造方法
private VolleyUtils(Context context) {
//创建RequestQueue,ImageLoader

File cacheDir = context.getCacheDir();//data/data/包名/cache/XXX

//sd卡下的Android/包名/files/images
File rootDirectory = context.getExternalFilesDir("images");
Cache cache = new DiskBasedCache(rootDirectory, 100 << 20);//100M 1024 = 2的十次方


Network network = getNetwork();
mRequestQueue = new RequestQueue(cache, network, 4);

mRequestQueue.start();//必须调用,不然没有网络请求

//ImageLoader
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {

LruCache<String, Bitmap> mLruCache =
new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {

//该方法,不重写,15×1024×1024
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};

@Override
public Bitmap getBitmap(String url) {
return mLruCache.get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
mLruCache.put(url, bitmap);
}
});
}

private Network getNetwork() {
Network network = null;
if (Build.VERSION.SDK_INT >= 9) {
network = new BasicNetwork(new HurlStack());//HttpUrlConnection,标准的网络请求
} else {
//如果api小于9,使用httpClient进行网络请求
network = new BasicNetwork(new HttpClientStack(new DefaultHttpClient()));
}
return network;
}
}

2.main方法进行实现

public class VolleyActivity extends AppCompatActivity {

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
mRequestQueue = VolleyUtils.getInstance(this).getRequestQueue();
mImageLoader = VolleyUtils.getInstance(this).getImageLoader();

mImageView = (ImageView) findViewById(R.id.image);
}

public void volley(View view) {

String url = "http://www.qq.com";
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("flag", "----------------->onResponse: 自定义的RequestQueue获取数据" + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("flag", "----------------->onErrorResponse: 失败" + error.getMessage());
}
});
mRequestQueue.add(request);

String imageUrl = "http://img01.taopic.com/150305/318754-15030510213437.jpg";

mImageLoader.get(imageUrl, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
mImageView.setImageBitmap(response.getBitmap());
}

@Override
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.mipmap.ic_launcher);
}
});


}
}

只是一只刚接触Volley框架的菜鸟,写了一个Demo,还是有很多收获的




知至者不如好知者,好知者不如乐知者!