什么是Volley
Google I/O 2013上恭陡,Volley發(fā)布了。Volley是Android平臺(tái)上的網(wǎng)絡(luò)通信庫,能使網(wǎng)絡(luò)通信更快赘方,更簡單缰泡,更健壯刀荒。
這是Volley名稱的由來: a burst or emission of many things or a large amount at once
特點(diǎn)
支持JSON,圖片,二進(jìn)制文本棘钞,內(nèi)存和磁盤緩存照棋,強(qiáng)力的自定義能力,debug和跟蹤工具
如何獲得武翎?
我在 云盤 放了編譯好的 http://yunpan.cn/cg7S8awftBsmp 訪問密碼 b1bf
怎么用烈炭?
1.構(gòu)建一個(gè)“請求隊(duì)列“RequestQueue
2.構(gòu)建請求Request,支持 StringRequest宝恶,JsonRequest,并可以自定義Request
3.構(gòu)建 回調(diào)監(jiān)聽器 符隙,它將在請求處理完成后被調(diào)用趴捅。
4.將請求添加到隊(duì)列
演示代碼
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方式發(fā)送參數(shù)
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();
}
};
}
注意傳參時(shí),是通過匿名類實(shí)現(xiàn)的霹疫,重載了getParams 方法
參考:
http://blog.csdn.net/t12x3456/article/details/9221611
me.storm.volley 示例