标签:
volley是谷歌官方在2013年推出的Android平台上的网络通信库
特点
异步处理
请求。排序处理
。缓存
。缺点
不适合数据的上传与下载
Get和Post请求接口的使用
请求对象
StringRequest request = new StringRequest(Request.Method.GET, REQUEST_URL, new Response.Listener<String>() {
@Override
public void onResponse(String s) {//数据请求成功
result.setText("请求成功:" + s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {//数据请求失败
result.setText("请求失败:" + volleyError.getMessage());
}
});
JSONObject jsonRequest = new JSONObject();//Get请求传递参数jsonRequest可以为空null
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, REQUEST_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
result.setText("请求成功:" + jsonObject);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
JsonArrayRequest request = new JsonArrayRequest(REQUEST_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
result.setText("请求成功:" + jsonArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
网络请求队列建立和取消队列建立
//创建请求队列
private static RequestQueue queues;
//初始化请求队列
queues = Volley.newRequestQueue(getApplicationContext());
MyApplication.getQueues().add(request);
MyApplication.getQueues().cancelAll(tag);
与Activity生命周期的联动
@Override
protected void onStop() {
super.onStop();
//结束请求
MyApplication.getQueues().cancelAll("StringRequest_get");
}
demo效果如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.xhb.app.MainActivity"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/_StringRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="StringRequestGet"
android:text="StringRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/StringRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/_StringRequestGet"
android:onClick="StringRequestPost"
android:text="StringRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/JsonObjectRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="JsonObjectRequestGet"
android:text="JsonObjectRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/JsonObjectRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/JsonObjectRequestGet"
android:onClick="JsonObjectRequestPost"
android:text="JsonObjectRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/JsonArrayRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="JsonArrayRequest"
android:text="JsonArrayRequest"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/MyRequestGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="MyRequestGet"
android:text="MyRequestGet"
android:textAllCaps="false"/>
<Button
android:id="@+id/MyRequestPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/MyRequestGet"
android:onClick="MyRequestPost"
android:text="MyRequestPost"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/ImageRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ImageRequest"
android:text="ImageRequest"
android:textAllCaps="false"/>
<Button
android:id="@+id/ImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/ImageRequest"
android:onClick="ImageLoader"
android:text="ImageLoader"
android:textAllCaps="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:id="@+id/image_imageRequest"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:textAllCaps="false"/>
<ImageView
android:id="@+id/image_iamgeLoader"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/image_imageRequest"
android:src="@mipmap/ic_launcher"
android:textAllCaps="false"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="请求结果为:"/>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
public class MyApplication extends Application {
//创建请求队列
private static RequestQueue queues;
@Override
public void onCreate() {
super.onCreate();
//初始书请求队列
queues = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getQueues() {
return queues;
}
}
public class MainActivity extends AppCompatActivity {
public static final String BASE = "http://op.juhe.cn/onebox/weather/query";
public static final String REQUEST_URL = BASE + "?cityname=%E5%8D%81%E5%A0%B0&key=634f562a2b3900e051c6af6e2dc3017e";
public static final String IMAGE_URL = "https://pic.cnblogs.com/avatar/789527/20160825180355.png";
private TextView result;
private ImageView image_imageRequest, image_iamgeLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
image_imageRequest = (ImageView) findViewById(R.id.image_imageRequest);
image_iamgeLoader = (ImageView) findViewById(R.id.image_iamgeLoader);
}
public void StringRequestGet(View view) {
//StringRequest
StringRequest request = new StringRequest(Request.Method.GET, REQUEST_URL, new Response.Listener<String>() {
@Override
public void onResponse(String s) {//数据请求成功
result.setText("请求成功:" + s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {//数据请求失败
result.setText("请求失败:" + volleyError.getMessage());
}
});
request.setTag("StringRequest_get");
MyApplication.getQueues().add(request);
}
public void StringRequestPost(View view) {
//StringRequest
StringRequest request = new StringRequest(Request.Method.POST, BASE, new Response.Listener<String>() {
@Override
public void onResponse(String s) {//数据请求成功
result.setText("请求成功:" + s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {//数据请求失败
result.setText("请求失败:" + volleyError.getMessage());
}
}) {
@Override//传递参数
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname", "十堰");
return map;
}
};
request.setTag("StringRequestPost");
MyApplication.getQueues().add(request);
}
public void JsonObjectRequestGet(View view) {
//JsonObjectRequest
JSONObject jsonRequest = new JSONObject();//Get请求传递参数jsonRequest可以为空null
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, REQUEST_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
result.setText("请求成功:" + jsonObject);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
request.setTag("JsonObjectRequestGet");
MyApplication.getQueues().add(request);
}
public void JsonObjectRequestPost(View view) {
Map<String, String> map = new HashMap<>();
map.put("key", "634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname", "十堰");
JSONObject jsonRequest = new JSONObject(map);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, BASE, jsonRequest, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
result.setText("请求成功:" + jsonObject.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
request.setTag("JsonObjectRequestPost");
MyApplication.getQueues().add(request);
}
public void JsonArrayRequest(View view) {
JsonArrayRequest request = new JsonArrayRequest(REQUEST_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
result.setText("请求成功:" + jsonArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
request.setTag("JsonArrayRequest");
MyApplication.getQueues().add(request);
}
public void MyRequestGet(View view) {
new VolleyRequest().RequestGet(this, REQUEST_URL, "MyRequestGet", new ResultBack(this, ResultBack.listener, ResultBack.errorListener) {
@Override
public void onSuccess(String s) {
result.setText("请求成功:" + s);
}
@Override
public void onFailure(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
}
public void MyRequestPost(View view) {
Map<String, String> map = new HashMap<>();
map.put("key", "634f562a2b3900e051c6af6e2dc3017e");
map.put("cityname", "十堰");
new VolleyRequest().RequestPost(this, REQUEST_URL, "MyRequestPost", map, new ResultBack(this, ResultBack.listener, ResultBack.errorListener) {
@Override
public void onSuccess(String s) {
result.setText("请求成功:" + s);
}
@Override
public void onFailure(VolleyError volleyError) {
result.setText("请求失败:" + volleyError.getMessage());
}
});
}
//ImageRequest方式加载图片
public void ImageRequest(View view) {
ImageRequest request = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {//加载成功
image_imageRequest.setImageBitmap(bitmap);
}
}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {//加载失败
@Override
public void onErrorResponse(VolleyError volleyError) {
image_imageRequest.setImageResource(R.mipmap.ic_launcher);
}
});
request.setTag("ImageRequest");
MyApplication.getQueues().add(request);
}
//ImageLoader加载图片
public void ImageLoader(View view) {
ImageLoader imageLoader = new ImageLoader(MyApplication.getQueues(), new BitmapCache());
ImageLoader.ImageListener listener = imageLoader.getImageListener(image_iamgeLoader, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
imageLoader.get(IMAGE_URL, listener);
}
@Override
protected void onStop() {
super.onStop();
//结束请求
MyApplication.getQueues().cancelAll("StringRequest_get");
}
}
public class VolleyRequest {
public static StringRequest stringRequest;
public static void RequestGet(Context context,String url,String tag,ResultBack reback){
MyApplication.getQueues().cancelAll(tag);
stringRequest=new StringRequest(Request.Method.GET, url,reback.loadingListener(),reback.errorListener());
stringRequest.setTag(tag);
MyApplication.getQueues().add(stringRequest);
MyApplication.getQueues().start();
}
public static void RequestPost(Context context, String url,String tag,final Map<String,String> map,ResultBack reback){
MyApplication.getQueues().cancelAll(tag);
stringRequest=new StringRequest(Request.Method.GET, url, reback.loadingListener(),reback.errorListener()){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return map;
}
};
stringRequest.setTag(tag);
MyApplication.getQueues().add(stringRequest);
MyApplication.getQueues().start();
}
}
自定义的回调接口
public abstract class ResultBack {
public Context context;
public static Response.Listener<String> listener;
public static Response.ErrorListener errorListener;
public ResultBack(Context context, Response.Listener<String> listener, Response.ErrorListener errorListener) {
this.context = context;
this.listener = listener;
this.errorListener = errorListener;
}
public Response.Listener<String> loadingListener() {
listener = new Response.Listener<String>() {
@Override
public void onResponse(String s) {
onSuccess(s);
}
};
return listener;
}
public Response.ErrorListener errorListener() {
errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
onFailure(volleyError);
}
};
return errorListener;
}
public abstract void onSuccess(String s);
public abstract void onFailure(VolleyError volleyError);
}
public class BitmapCache implements ImageLoader.ImageCache {
public LruCache<String,Bitmap> mBitmapLruCache;
public int max=1024*1024*10;// 最大缓存10M,超过就会回收
public BitmapCache(){
mBitmapLruCache=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 mBitmapLruCache.get(s);
}
@Override
public void putBitmap(String s, Bitmap bitmap) {
mBitmapLruCache.put(s,bitmap);
}
}
标签:
原文地址:http://www.cnblogs.com/wisemen/p/5835918.html