什么是Volley
Google I/O 2013上,Volley发布了。Volley是Android平台上的网络通信库,能使网络通信更快,更简单,更健壮。
这是Volley名称的由来: a burst or emission of many things or a large amount at once
特点
支持JSON,图片,二进制文本,内存和磁盘缓存,强力的自定义能力,debug和跟踪工具
如何获得?
我在 云盘 放了编译好的 http://yunpan.cn/cg7S8awftBsmp 访问密码 b1bf
怎么用?
1.构建一个“请求队列“RequestQueue
2.构建请求Request,支持 StringRequest,JsonRequest,并可以自定义Request
3.构建 回调监听器 ,它将在请求处理完成后被调用。
4.将请求添加到队列
演示代码
HTTP GET 演示:
public class SimpleGetActivity extends Activity {
RequestQueue mRequestQueue;
TextView txt_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_get);
txt_msg = (TextView) findViewById(R.id.txt_msg);
mRequestQueue = Volley.newRequestQueue(this);
}
public void btn1OnClick(View v) {
String url = "http://www.baidu.com";
StringRequest req = new StringRequest(Method.GET, url,
responseListener, mErrorListener);
mRequestQueue.add(req);
}
Listener<String> responseListener =new Listener<String>() {
@Override
public void onResponse(String str1) {
txt_msg.setText(str1);
}
};
ErrorListener mErrorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getBaseContext(), volleyError.getMessage(), 0).show();
}
};
}
HTTP POST方式发送参数
public class ParasPostActivity extends Activity {
RequestQueue mRequestQueue;
TextView txt_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paras_post);
txt_msg = (TextView) findViewById(R.id.txt_msg);
mRequestQueue = Volley.newRequestQueue(this);
}
public void btn1OnClick(View v) {
String url = Constants.URL_FOR_DEMO1;
StringRequest req = new StringRequest(Method.POST, url,
responseListener, mErrorListener){
@Override
protected Map<String, String> getParams()
throws AuthFailureError {
return new ApiParams().with("key1", "v1").with("key2", "v2");
}
};
mRequestQueue.add(req);
}
Listener<String> responseListener =new Listener<String>() {
@Override
public void onResponse(String str1) {
txt_msg.setText(str1);
}
};
ErrorListener mErrorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getBaseContext(), volleyError.getMessage(), 0).show();
}
};
}
注意传参时,是通过匿名类实现的,重载了getParams 方法
参考:
http://blog.csdn.net/t12x3456/article/details/9221611
me.storm.volley 示例