What is a Volley
At Google I/O 2013, Volley was released. Volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust. That’s how Volley got its name: a burst or emission of many things or a large amount at once
The characteristics of
Support for JSON, images, binary text, memory and disk caching, powerful customization capabilities, debug and trace tools
How to get it?
I put a compiled yunpan.cn/cg7S8awftBs in the cloud disk… Access password b1bf
How does it work?
- Build a “RequestQueue” RequestQueue
- Build Request Request, support StringRequest, JsonRequest, and can customize Request
- Build a callback listener that will be invoked after the request processing is complete.
- Add the request to the queue
Demo code
A simple HTTP GET demo:
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(); }}; }Copy the code
Send parameters in POST mode
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(); }}; }Copy the code
Note that the parameter is passed through an anonymous class, overloading the getParams method
Reference:
Blog.csdn.net/t12x3456/ar…
Me. Storm. Volley example