Volley的使用总结

Volley可以非常简单地进行HTTP通信,也可以加载网络图片,适用进行数据量不大,但是通信频繁的网络操作,对于大数据量的网络操作,比如说下载文件等,Volley就比较糟糕。

StringRequest的用法

//1.创建RequestQueue对象。
RequestQueue mQueue = Volley.newRequestQueue(context);
//RequestQueue 是一个请求队列对象,可以缓存所有的HTTP请求,然后按照一定的算法并发地发出这些请求。内部设计就是非常适合高并发的,基本上在每一个需要和网络交互的Activity中创建一个RequestQueue对象就可以了。

//2.创建StringRequest对象
StringRequest stringRequest = new StringRequest("https://ww.baidu.com",
new Response.Listener(){
    @Override
    public void onResponse(String response){
    }}, new Response.ErrorListener(){
      @Override
     public void onErrorResponse(VolleyError error){
     }
});

//3.将StringRequest对象添加到RequestQueue。
mQueue.add(stringRequest);

//POST请求方式
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener){
    @Override
     protected Map getParams() throws AuthFailureError{
          Map map = new HashMap<>();
          map.put("params1", "value1");
          map.put("params2", "value2");
          return map;
      }
};

JsonRequest的用法

有两个子类JsonObjectRequest和JsonArrayRequest。

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://ww.baidu.com",null,
new Response.Listener(){
    @Override
    public void onResponse(JSONObject response){
    }}, new Response.ErrorListener(){
      @Override
     public void onErrorResponse(VolleyError error){
     }
});

mQueue.add(jsonObjectRequest);

//JsonArrayRequest同理

ImageRequest的用法

ImageRequest imageRequest = new ImageRequest(
"http://developer.android.com/images/home/aw_dac.png",
new Response.Listener() {
@Override
public void onResponse(Bitmap response) {
imageView.setImageBitmap(response);
}
}, 0, 0, Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
imageView.setImageResource(R.drawable.default_image);
}
});

//其中第三第四个参数,分别是指定允许图片的最大的宽度和高度。
指定0就不管图片多大,都不会压缩。

ImageLoader的用法

ImageLoader明显要比ImageRequest更加高效,它不仅帮我们对图片进行缓存,还过滤重复的链接,避免重复发送请求。
主要步骤:
1、创建一个RequestQueue对象
2、创建一个ImageLoader对象
3、获取一个ImageListenre对象
4、调用ImageLoader的get()方法加载网络上的图片。

RequestQueue mQueue = Volley.newRequestQueue(context);

//自定义一个图片缓存
public class BitmapCache implements ImageCache {
private LruCache mCache;
public BitmapCache() {
int maxSize = 10 * 1024 * 1024;
mCache = new LruCache(maxSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
}



ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());

ImageListener listener = ImageLoader.getImageListener(imageView, R,drawable.default_image, R.drawable.failed_image);

imageLoader.get("http://adbdd/adb.png", listener);
//或,指定允许的最大宽高
imageLoader.get("http://adbdd/adb.png", listener, 200,200);

NetworkImageView的用法

NetworkImageView是一个自定义控件,继承自ImageView,具备它所有的功能,并在原生的基础上加入了加载网络图片的功能。
1、创建一个ReqestQueue对象
2、创建一个ImageLoader对象
3、在布局文件中添加一个NetworkImageView控件
4、代码中获取该控件的实例
5、设置要加载的图片地址

其中第一二步和上面相同。


自定义XMLRequest

public class XMLRequest extends Request {
private final Listener mListener;
public XMLRequest(int method, String url, Listener listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
}
public XMLRequest(String url, Listener listener, ErrorListener errorListener) {
this(Method.GET, url, listener, errorListener);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String xmlString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlString));
return Response.success(xmlPullParser, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (XmlPullParserException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(XmlPullParser response) {
mListener.onResponse(response);
}
}


XMLRequest xmlRequest = new XMLRequest(
"http://flash.weather.com.cn/wmaps/xml/china.xml",
new Response.Listener() {
@Override
public void onResponse(XmlPullParser response) {
try {
int eventType = response.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
String nodeName = response.getName();
if ("city".equals(nodeName)) {
String pName = response.getAttributeValue(0);
Log.d("TAG", "pName is " + pName);
}
break;
}
eventType = response.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(xmlRequest);

自定义GsonRequest

//把gson的jar包添加到项目中
public class GsonRequest extends Request {
private final Listener mListener;
private Gson mGson;
private Class mClass;
public GsonRequest(int method, String url, Class clazz, Listener listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mGson = new Gson();
mClass = clazz;
mListener = listener;
}
public GsonRequest(String url, Class clazz, Listener listener,
ErrorListener errorListener) {
this(Method.GET, url, clazz, listener, errorListener);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}

public class Weather {
private WeatherInfo weatherinfo;
public WeatherInfo getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(WeatherInfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
}

public class WeatherInfo {
private String city;
private String temp;
private String time;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

GsonRequest gsonRequest = new GsonRequest(
"http://www.weather.com.cn/data/sk/101010100.html", Weather.class,
new Response.Listener() {
@Override
public void onResponse(Weather weather) {
WeatherInfo weatherInfo = weather.getWeatherinfo();
Log.d("TAG", "city is " + weatherInfo.getCity());
Log.d("TAG", "temp is " + weatherInfo.getTemp());
Log.d("TAG", "time is " + weatherInfo.getTime());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(gsonRequest);


来源:https://www.jishudog.com/22298/html

你可能感兴趣的:(Volley的使用总结)