• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Make a standard request
2
3This lesson describes how to use the common request types that Volley supports:
4
5- `StringRequest`. Specify a URL and receive a raw string in response. See
6  [Set up a RequestQueue](requestqueue.md) for an example.
7- `JsonObjectRequest` and `JsonArrayRequest` (both subclasses of
8  `JsonRequest`). Specify a URL and get a JSON object or array (respectively) in
9  response.
10
11If your expected response is one of these types, you probably don't have to implement a
12custom request. This lesson describes how to use these standard request types. For
13information on how to implement your own custom request, see
14[Implement a custom request](./request-custom.md).
15
16## Request JSON
17
18Volley provides the following classes for JSON requests:
19
20- `JsonArrayRequest`: A request for retrieving a
21  [`JSONArray`](https://developer.android.com/reference/org/json/JSONArray)
22  response body at a given URL.
23- `JsonObjectRequest`: A request for retrieving a
24  [`JSONObject`](https://developer.android.com/reference/org/json/JSONObject)
25  response body at a given URL, allowing for an optional
26  [`JSONObject`](https://developer.android.com/reference/org/json/JSONObject)
27  to be passed in as part of the request body.
28
29Both classes are based on the common base class `JsonRequest`. You use them
30following the same basic pattern you use for other types of requests. For example, this
31snippet fetches a JSON feed and displays it as text in the UI:
32
33*Kotlin*
34
35```kotlin
36val url = "http://my-json-feed"
37
38val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
39        Response.Listener { response ->
40            textView.text = "Response: %s".format(response.toString())
41        },
42        Response.ErrorListener { error ->
43            // TODO: Handle error
44        }
45)
46
47// Access the RequestQueue through your singleton class.
48MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
49```
50
51*Java*
52
53```java
54String url = "http://my-json-feed";
55
56JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
57        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
58
59    @Override
60    public void onResponse(JSONObject response) {
61        textView.setText("Response: " + response.toString());
62    }
63}, new Response.ErrorListener() {
64
65    @Override
66    public void onErrorResponse(VolleyError error) {
67        // TODO: Handle error
68
69    }
70});
71
72// Access the RequestQueue through your singleton class.
73MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
74```
75
76For an example of implementing a custom JSON request based on
77[Gson](https://github.com/google/gson), see the next lesson,
78[Implement a custom request](request-custom.md).
79