Home | History | Annotate | Download | only in volley
      1 page.title=Sending a Simple Request
      2 
      3 trainingnavtop=true
      4 
      5 @jd:body
      6 
      7 <div id="tb-wrapper">
      8 <div id="tb">
      9 
     10 <!-- table of contents -->
     11 <h2>This lesson teaches you to</h2>
     12 <ol>
     13   <li><a href="#manifest">Add the INTERNET Permission</a></li>
     14   <li><a href="#simple">Use newRequestQueue</a></li>
     15   <li><a href="#send">Send a Request</a></li>
     16   <li><a href="#cancel">Cancel a Request</a></li>
     17 </ol>
     18 
     19 </div>
     20 </div>
     21 
     22 <a class="notice-developers-video wide" href="https://developers.google.com/events/io/sessions/325304728">
     23 <div>
     24     <h3>Video</h3>
     25     <p>Volley: Easy, Fast Networking for Android</p>
     26 </div>
     27 </a>
     28 
     29 <p>At a high level, you use Volley by creating a {@code RequestQueue} and passing it
     30 {@code Request} objects. The {@code RequestQueue} manages worker threads for running the
     31 network operations, reading from and writing to the cache, and parsing responses. Requests
     32 do the parsing of raw responses and Volley takes care of dispatching the parsed response
     33 back to the main thread for delivery.</p>
     34 
     35 <p> This lesson describes how to send a request using the <code>Volley.newRequestQueue</code>
     36 convenience method, which sets up a {@code RequestQueue} for you.
     37 See the next lesson,
     38 <a href="requestqueue.html">Setting Up a RequestQueue</a>, for information on how to set
     39 up a {@code RequestQueue} yourself.</p>
     40 
     41 <p>This lesson also describes how to add a request to a {@code RequestQueue} and cancel a
     42 request.</p>
     43 
     44 <h2 id="manifest">Add the INTERNET Permission</h2>
     45 
     46 <p>To use Volley, you must add the
     47 {@link android.Manifest.permission#INTERNET android.permission.INTERNET} permission
     48 to your app's manifest. Without this, your app won't be able to connect to the network.</p>
     49 
     50 
     51 <h2 id="simple">Use newRequestQueue</h2>
     52 
     53 <p>Volley provides a convenience method <code>Volley.newRequestQueue</code> that sets up a
     54 {@code RequestQueue} for you, using default values, and starts the queue. For example:</p>
     55 
     56 <pre>
     57 final TextView mTextView = (TextView) findViewById(R.id.text);
     58 ...
     59 
     60 // Instantiate the RequestQueue.
     61 RequestQueue queue = Volley.newRequestQueue(this);
     62 String url ="http://www.google.com";
     63 
     64 // Request a string response from the provided URL.
     65 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
     66             new Response.Listener<String>() {
     67     &#64;Override
     68     public void onResponse(String response) {
     69         // Display the first 500 characters of the response string.
     70         mTextView.setText("Response is: "+ response.substring(0,500));
     71     }
     72 }, new Response.ErrorListener() {
     73     &#64;Override
     74     public void onErrorResponse(VolleyError error) {
     75         mTextView.setText("That didn't work!");
     76     }
     77 });
     78 // Add the request to the RequestQueue.
     79 queue.add(stringRequest);
     80 </pre>
     81 
     82 <p>Volley always delivers parsed responses on the main thread. Running on the main thread
     83 is convenient for populating UI controls with received data, as you can freely modify UI
     84 controls directly from your response handler, but it's especially critical to many of the
     85 important semantics provided by the library, particularly related to canceling requests.
     86 </p>
     87 
     88 <p>See <a href="requestqueue.html">Setting Up a RequestQueue</a> for a
     89 description of how to set up a {@code RequestQueue} yourself, instead of using the
     90 <code>Volley.newRequestQueue</code> convenience method.</p>
     91 
     92 <h2 id="send">Send a Request</h2>
     93 
     94 <p>To send a request, you simply construct one and add it to the {@code RequestQueue} with
     95 {@code add()}, as shown above. Once you add the request it moves through the pipeline,
     96 gets serviced, and has its raw response parsed and delivered.</p>
     97 
     98 <p>When you call {@code add()}, Volley runs one cache processing thread and a pool of
     99 network dispatch threads. When you add a request to the queue, it is picked up by the cache
    100 thread and triaged: if the request can be serviced from cache, the cached response is
    101 parsed on the cache thread and the parsed response is delivered on the main thread. If the
    102 request cannot be serviced from cache, it is placed on the network queue. The first
    103 available network thread takes the request from the queue, performs the HTTP transaction,
    104 parsse the response on the worker thread, writes the response to cache, and posts the parsed
    105 response back to the main thread for delivery.</p>
    106 
    107 <p>Note that expensive operations like blocking I/O and parsing/decoding are done on worker
    108 threads. You can add a request from any thread, but responses are always delivered on the
    109 main thread.</p>
    110 
    111 <p>Figure 1 illustrates the life of a request:</p>
    112 
    113  <img src="{@docRoot}images/training/volley-request.png"
    114   alt="system bars">
    115 <p class="img-caption"><strong>Figure 1.</strong> Life of a request.</p>
    116 
    117 
    118 <h2 id="cancel">Cancel a Request</h2>
    119 
    120 <p>To cancel a request, call {@code cancel()} on your {@code Request} object. Once cancelled,
    121 Volley guarantees that your response handler will never be called. What this means in
    122 practice is that you can cancel all of your pending requests in your activity's
    123 {@link android.app.Activity#onStop onStop()} method and you don't have to litter your
    124 response handlers with checks for {@code getActivity() == null},
    125 whether {@code onSaveInstanceState()} has been called already, or other defensive
    126 boilerplate.</p>
    127 
    128 <p>To take advantage of this behavior, you would typically have to
    129 track all in-flight requests in order to be able to cancel them at the
    130 appropriate time. There is an easier way: you can associate a tag object with each
    131 request. You can then use this tag to provide a scope of requests to cancel. For
    132 example, you can tag all of your requests with the {@link android.app.Activity} they
    133 are being made on behalf of, and call {@code requestQueue.cancelAll(this)} from
    134 {@link android.app.Activity#onStop onStop()}.
    135 Similarly, you could tag all thumbnail image requests in a
    136 {@link android.support.v4.view.ViewPager} tab with their respective tabs and cancel on swipe
    137 to make sure that the new tab isn't being held up by requests from another one.</p>
    138 
    139 <p>Here is an example that uses a string value for the tag:</p>
    140 
    141 <ol>
    142 <li>Define your tag and add it to your requests.
    143 <pre>
    144 public static final String TAG = "MyTag";
    145 StringRequest stringRequest; // Assume this exists.
    146 RequestQueue mRequestQueue;  // Assume this exists.
    147 
    148 // Set the tag on the request.
    149 stringRequest.setTag(TAG);
    150 
    151 // Add the request to the RequestQueue.
    152 mRequestQueue.add(stringRequest);</pre>
    153 </li>
    154 
    155 <li>In your activity's {@link android.app.Activity#onStop onStop()} method, cancel all requests that have this tag.
    156 <pre>
    157 &#64;Override
    158 protected void onStop () {
    159     super.onStop();
    160     if (mRequestQueue != null) {
    161         mRequestQueue.cancelAll(TAG);
    162     }
    163 }
    164 </pre></li></ol>
    165 
    166 <p>Take care when canceling requests. If you are depending on your response handler to
    167 advance a state or kick off another process, you need to account for this. Again, the
    168 response handler will not be called.
    169 </p>
    170