Android开源框架Volley的使用

时间:2021-12-08 15:28:52

一、概述
Volley是google发布的一款android网络通信库,它适合效率要求较高场景以及并发场景。它有如下特点:

  • 通信更快、更简单、更健壮。开发效率会得到很大提升,稳定性也会很高。
  • GET、POST请求及网络图像的高效率异步处理
  • 可以对网络请求进行排序和优先级处理。
  • 网络请求的缓存。
  • 多级别取消请求。
  • 和Activity生命周期的联动。当activity销毁时,可通过
  • 不适合网络数据的上传和下载

二、网络数据请求

首先,要自定义一个Application,初始化一个Volley请求队列。并将Application注册到manifest文件中。还要添加网络权限。

public class MyApplication extends Application {
public static RequestQueue queue;
@Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext());
}

public static RequestQueue getHttpQueue() {
return queue;
}
}
  • StringRequest
//POST请求
private void volleyPost() {
String url = "";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
//请求成功的操作
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//请求失败的操作
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("phone", "13838383838");
hashMap.put("key", "sbsbsbsb");
return hashMap;
}
};
request.setTag("abcPost");
MyApplication.getHttpQueues().add(request);
//GET请求
private void volleyGet() {
String url = "http://.......?phone=13838383838&key=sbsbsbsbsb";
//1.String
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
});
request.setTag("abcGet");
MyApplication.getHttpQueues().add(request);
  • JsonObjectRequest
//POST
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("phone", "13838383838");
hashMap.put("key", "sbsbsbsb");
JSONObject object = new JSONObject(hashMap);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {

}
});
request.setTag("abcPost");
MyApplication.getHttpQueues().add(request);
//GET
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//请求成功的操作
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// 请求失败的操作
}
});
request.setTag("abcGet");
MyApplication.getHttpQueues().add(request);
  • JsonArrayRequest

和JsonObjectRequest大同小异,略。

三、获取网络图片

首先做一下准备工作。。。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/iv_img"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/net_iv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"/>

</RelativeLayout>
//去manifest.xml中注册和添加权限
public class MyApplication extends Application {
public static RequestQueue queue;
@Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext());
}

public static RequestQueue getHttpQueue() {
return queue;
}
}
iv_img = (ImageView) this.findViewById(R.id.iv_img);
networkIv = (NetworkImageView) this.findViewById(R.id.net_iv);
String url = "http://www.baidu.com/img/bdlogo.png";
/**
* 使用ImageRequest请求网络图片
*/

mageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
iv_img.setImageBitmap(bitmap);
}
}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
iv_img.setBackgroundResource(R.mipmap.ic_launcher);
}
});
MyApplication.getHttpQueue().add(request);
/**
* 使用ImageLoader缓存网络图片
*/

ImageLoader loader = new ImageLoader(MyApplication.getHttpQueue(), new BitmapCache());
ImageLoader.ImageListener listener = ImageLoader.getImageListener(iv_img, R.mipmap.ic_launcher,
R.mipmap.ic_launcher);
loader.get(url, listener);
public class BitmapCache implements ImageLoader.ImageCache {
public LruCache<String, Bitmap> cache;
public int max = 10 * 1024 * 1024; //设置最大缓存大小

public BitmapCache() {
cache = new LruCache<String, Bitmap>(max) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
}

@Override
public Bitmap getBitmap(String s) {
return cache.get(s);
}

@Override
public void putBitmap(String s, Bitmap bitmap) {
cache.put(s, bitmap);
}
}
/**
* 使用NetworkImageView加载网络图片
*/

ImageLoader loader = new ImageLoader(MyApplication.getHttpQueue(), new BitmapCache());
networkIv.setDefaultImageResId(R.mipmap.ic_launcher);
networkIv.setErrorImageResId(R.mipmap.ic_launcher);
networkIv.setImageUrl(url, loader);

NetWorkResponse类

/**
* Data and headers returned from {@link Network#performRequest(Request)}.
*/

public class NetworkResponse {
/**
* Creates a new network response.
* @param statusCode the HTTP status code
* @param data Response body
* @param headers Headers returned with this response, or null for none
* @param notModified True if the server returned a 304 and the data was already in cache
* @param networkTimeMs Round-trip network time to receive network response
*/

public NetworkResponse(int statusCode, byte[] data, Map<String, String> headers,
boolean notModified, long networkTimeMs) {
this.statusCode = statusCode;
this.data = data;
this.headers = headers;
this.notModified = notModified;
this.networkTimeMs = networkTimeMs;
}

public NetworkResponse(int statusCode, byte[] data, Map<String, String> headers,
boolean notModified) {
this(statusCode, data, headers, notModified, 0);
}

public NetworkResponse(byte[] data) {
this(HttpStatus.SC_OK, data, Collections.<String, String>emptyMap(), false, 0);
}

public NetworkResponse(byte[] data, Map<String, String> headers) {
this(HttpStatus.SC_OK, data, headers, false, 0);
}

/** The HTTP status code. */
public final int statusCode;

/** Raw data from this response. */
public final byte[] data;

/** Response headers. */
public final Map<String, String> headers;

/** True if the server returned a 304 (Not Modified). */
public final boolean notModified;

/** Network roundtrip time in milliseconds. */
public final long networkTimeMs;
}