特点:
缺点:
不适合数据的上传和下载,不适合大数据和流媒体的网络请求。
基本介绍:
1.Volley的get和post请求方式的使用:
StringRequest:对请求的数据返回结果类型不确定时使用
JsonObjectRequest:确定返回数据为JsonObject类型时使用
JsonArrayRequest:确定返回的数据是JsonArray时使用
2.回调的使用:
当我们请求成功,失败,请求重试等回调方法
3.Volley的网络请求队列的建立和取消队列请求:
在使用Volley时,首先要建立一个全局的请求队列。然后在建立请求,将请求加入请求队列中,这样整个app的请求是通过这个队列来管理的,方便取消某个请求或者取消所有请求的操作。
4.Volley和Activity生命周期的联动:
volley请求的生命周期与Activity的生命周期是关联在一起的。可以在Activity销毁时,同时关闭请求,防止在后台运行这个请求,造成内存溢出。
在volley请求的生命周期与Activity的生命周期关联的时候,设置Tag标签,因为请求的关闭需要通过Tag标签在请求队列中查找,然后再Activity的onStop()方法里执行取消请求。
5.Volley的简单的二次回调封装:
使用自定义的,方便进行全局的管理
Volley框架基本使用方法例子:
package com.example.volleytest1;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Volley是Android平台网络通信库:更快,更简单,更健壮
*
* @author Administrator
*
*/
public class MainActivity extends Activity {
private ImageView imageView;
private NetworkImageView networkImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
getJSONVolley();
loadImageVolley();
NetWorkImageViewVolley();
}
private void initView() {
imageView = (ImageView) findViewById(R.id.imageView);
networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
}
// 使用Volley做Json字符串的请求
public void getJSONVolley() {
//建立请求队列
RequestQueue requestQueue = Volley.newRequestQueue(this);
String JSONDateUrl = "http://apis.juhe.cn/mobile/get?";
//参数意义:请求方式、Url、请求成功的回调方法,请求失败的回调方法
StringRequest jsonObjectRequest = new StringRequest(Method.POST,
JSONDateUrl, new Response.Listener() {
@Override
public void onResponse(String arg0) {
System.out.println(arg0);
Toast.makeText(MainActivity.this, arg0, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
System.out.println(arg0.toString());
Toast.makeText(MainActivity.this, arg0.toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map getParams()
throws AuthFailureError {
Map map = new HashMap();
map.put("phone", "15211807740");
map.put("key", "2d35800313209bff48674f203fb38b91");
return map;
}
};
//设置Tag标签
jsonObjectRequest.setTag("aaa");
//将请求加入到请求队列中
requestQueue.add(jsonObjectRequest);
}
//使用Volley做图片的请求
public void loadImageVolley() {
String url = "http://g.hiphotos.baidu.com/image/pic/item/c2fdfc039245d688427eb40ca1c27d1ed21b241d.jpg";
RequestQueue requestQueue = Volley.newRequestQueue(this);
final LruCache lurCache = new LruCache(
20);
ImageCache imageCache = new ImageCache() {
@Override
public void putBitmap(String key, Bitmap value) {
lurCache.put(key, value);
}
@Override
public Bitmap getBitmap(String key) {
return lurCache.get(key);
}
};
ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
ImageListener listener = imageLoader.getImageListener(imageView,
R.drawable.ic_launcher, R.drawable.ic_launcher);
imageLoader.get(url, listener);
}
//使用NetWorkImageView完成图片加载
//NetWorkImageView是Volley提供的一个控件,是用来替代ImageView的
//NetWorkImageVIew控件的优点:当父类控件dispatch时,NetWorkImageView控件会自动取消网络请求,所以不用担心生命周期问题
public void NetWorkImageViewVolley(){
String imageUrl = "http://img2.3lian.com/2014/f7/5/d/22.jpg";
RequestQueue requestQueue = Volley.newRequestQueue(this);
final LruCache lruCache = new LruCache(20);
ImageCache imageCache = new ImageCache() {
@Override
public void putBitmap(String key, Bitmap value) {
lruCache.put(key, value);
}
@Override
public Bitmap getBitmap(String key) {
return lruCache.get(key);
}
};
ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
networkImageView.setTag("networkimageview");
networkImageView.setImageUrl(imageUrl, imageLoader);
}
}
运行结果:
对上边代码中 使用Volley做Json字符串的请求部分 的回调做二次回调封装:
SecondActivity类:
package com.test.volleytest2;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.example.volleytest1.R;
public class SecondActivity extends Activity {
private EditText editText;
private Button button;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initView();
setOnListener();
}
private void setOnListener() {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("");
getJSONVolley();
}
});
}
private void initView() {
editText = (EditText) findViewById(R.id.id_edittext);
button = (Button) findViewById(R.id.id_button);
textView = (TextView) findViewById(R.id.id_textview);
}
private void getJSONVolley() {
String phone = editText.getText().toString();
String key = "2d35800313209bff48674f203fb38b91";
String url = "http://apis.juhe.cn/mobile/get?";
Map map = new HashMap();
map.put("phone", phone);
map.put("key", key);
RequestUtils.getVolley(SecondActivity.this, url, map,new MyListener() {
@Override
public void success(String info) {
System.out.println(info);
textView.setText(info);
}
@Override
public void failure(VolleyError errorInfo) {
System.out.println(errorInfo.toString());
textView.setText(errorInfo.toString());
}
});
}
}
RequestUtils类:
package com.test.volleytest2;
import java.util.Map;
import android.content.Context;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class RequestUtils {
public static void getVolley(Context context,String url,final Map map,MyListener listener){
RequestQueue queues = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Method.POST, url, listener.requestSuccess(), listener.requestFailure()){
@Override
protected Map getParams() throws AuthFailureError {
return map;
}
};
stringRequest.setTag("abc");
queues.add(stringRequest);
queues.start();
}
}
MyListener类:
package com.test.volleytest2;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
public abstract class MyListener{
private Listener listener;
private ErrorListener errorListener;
public abstract void success(String info);
public abstract void failure(VolleyError errorInfo);
public Listener requestSuccess(){
listener = new Listener() {
@Override
public void onResponse(String arg0) {
success(arg0);
}
};
return listener;
}
public ErrorListener requestFailure(){
errorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
failure(arg0);
}
};
return errorListener;
}
}
高效的网络数据请求,文件的上传和下载
特点:
二进制文件(图片等)的下载,使用BinaryHttpResponseHandler
使用Get/Post请求数据的基本操作:
package com.example.asncyhttptest;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// asynchttpGet();
asynchttpPost();
}
// 使用Post方式请求
private void asynchttpPost() {
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://apis.juhe.cn/mobile/get?";
RequestParams params = new RequestParams();
params.put("phone", "15211807740");
params.put("key", "2d35800313209bff48674f203fb38b91");
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
// 请求失败
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
System.out.println(arg0.toString());
}
@Override
// 请求成功
public void onSuccess(String arg0) {
super.onSuccess(arg0);
System.out.println(arg0);
}
});
}
// 使用Get方式请求
private void asynchttpGet() {
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://apis.juhe.cn/mobile/get?phone=15211807740&key=2d35800313209bff48674f203fb38b91";
client.get(url, new AsyncHttpResponseHandler() {
@Override
// 请求失败
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
System.out.println(arg0.toString());
}
@Override
// 请求成功
public void onSuccess(String arg0) {
super.onSuccess(arg0);
System.out.println(arg0);
}
});
}
}
对上边例子中的Get/Post方法中的请求回调进行二次封装:
SecondActivity类:
package com.test.asncyhttptest;
import com.example.asncyhttptest.R;
import com.loopj.android.http.RequestParams;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asynchttpGet();
asynchttpPost();
}
//使用Post方法请求
private void asynchttpPost() {
String postUrl = "http://apis.juhe.cn/mobile/get?";
RequestParams params = new RequestParams();
params.put("phone", "15211807740");
params.put("key", "2d35800313209bff48674f203fb38b91");
RequestUtils.ClientPost(postUrl, params, new NetCallBack() {
@Override
public void RequestSuccess(String info) {
System.out.println("POST:"+info);
}
@Override
public void RequestFailure(String info) {
System.out.println("POST"+info);
}
});
}
//使用Get方式请求
private void asynchttpGet() {
String getUrl = "http://apis.juhe.cn/mobile/get?phone=15211807740&key=2d35800313209bff48674f203fb38b91";
RequestUtils.ClientGet(getUrl, new NetCallBack() {
@Override
public void RequestSuccess(String info) {
System.out.println("GET:"+info);
}
@Override
public void RequestFailure(String info) {
System.out.println("GET:"+info);
}
});
}
}
RequestUtils类:
package com.test.asncyhttptest;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
public class RequestUtils {
public static AsyncHttpClient client = new AsyncHttpClient();
public static void ClientGet(String url,NetCallBack callback){
client.get(url, callback);
}
public static void ClientPost(String url,RequestParams params,NetCallBack callback){
client.post(url, params, callback);
}
}
NetCallBack类:
package com.test.asncyhttptest;
import com.loopj.android.http.AsyncHttpResponseHandler;
public abstract class NetCallBack extends AsyncHttpResponseHandler{
public abstract void RequestSuccess(String info);
public abstract void RequestFailure(String info);
@Override
public void onStart() {
super.onStart();
System.out.println("请求开始");
}
@Override
public void onSuccess(String arg0) {
super.onSuccess(arg0);
System.out.println("请求成功");
RequestSuccess(arg0);
}
@Override
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
System.out.println("请求失败");
RequestFailure(arg0.toString());
}
}