博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Volley
阅读量:7074 次
发布时间:2019-06-28

本文共 4119 字,大约阅读时间需要 13 分钟。

Volley - Android HTTP client

Part 1 - Quickstart

Were can I get it?

Download volley library and import it as a library project or make a jar file.

git clone https://android.googlesource.com/platform/frameworks/volley

Why Volley?

  • Simple

  • Powerful

  • Extendable

  • Built-in memory cache

  • Built-in disk cache

How to use it?

Step 1 - Create request queue

RequestQueue requestQueue = Volley.newRequestQueue(context.getApplicationContext());

Step 2 - Create request

StringRequest request = new StringRequest(            Request.Method.GET,            url,            listener,            errorListener);

Step 3 - Create listeners

Response.Listener
 listener = new Response.Listener
() {    @Override    public void onResponse(String response) {        L.d("Success Response: " + response.toString());    }};Response.ErrorListener errorListener = new Response.ErrorListener() {    @Override    public void onErrorResponse(VolleyError error) {        if (error.networkResponse != null) {            L.d("Error Response code: " +  error.networkResponse.statusCode);        }    }};

Step 4 - Add request to queue

requestQueue.add(request);

Request methods:

  • Request.Method.GET

  • Request.Method.POST

  • Request.Method.PUT

  • Request.Method.DELETE

Request types:

Every request listener returns appropriate type.

  • String

  • Json Object

  • Json Array

  • Bitmap

You can create your own type

Example of request which adds some cookie.

public class CookieRequest extends StringRequest {    private String mCookieValue;        public CookieRequest(String url, String cookieValue,                Response.Listener
 listener,                Response.ErrorListener errorListener) {            super(Method.GET, url, listener, errorListener);            mCookieValue = cookieValue;        }        @Override        public Map
 getHeaders() throws AuthFailureError {            Map
 map = new HashMap
();            map.put("Cookie", mCookieValue);            return map;        }}

How to pass post request parameters?

You need to override getParams() method.

StringRequest request = new StringRequest(        Request.Method.POST,        url,        listener,        errorListener) {    @Override    protected Map
 getParams() throws AuthFailureError {        Map
 map = new HashMap
();        map.put("name", "Jon Doe");        map.put("age", "21");        return map;    }};

How to set request retry policy?

StringRequest request = new StringRequest(        Request.Method.GET,        url,        listener,        errorListener);request.setRetryPolicy(    new DefaultRetryPolicy(            DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, // 2500            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 1            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); //1f

HTTP basic authorization

StringRequest request = new StringRequest(        Request.Method.GET,        url,        listener,        errorListener) {    @Override    public Map
 getHeaders() throws AuthFailureError {        return createBasicAuthHeader("user", "passwd");    }};
Map
 createBasicAuthHeader(String username, String password) {    Map
 headerMap = new HashMap
();    String credentials = username + ":" + password;    String base64EncodedCredentials =            Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);    headerMap.put("Authorization", "Basic " + base64EncodedCredentials);    return headerMap;}

How to cancel request?

StringRequest request1 = new StringRequest(...);request1.setTag("weather-screen"); // request tagStringRequest request2 = new StringRequest(...);request2.setTag("weather-screen"); // request tagrequestQueue.add(request1);requestQueue.add(request2);

To cancel request you just need to remember request tag and call cancelAll(...) method.

requestQueue.cancelAll("weather-screen"); // cancel all requests with "weather-screen" tag

SEE ALSO:

本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/1661624,如需转载请自行联系原作者
你可能感兴趣的文章