本课介绍了如何使用 Volley 支持的常见请求类型:
StringRequest
。指定网址并接收响应中的原始字符串。请参阅设置请求队列查看示例。JsonObjectRequest
和JsonArrayRequest
(JsonRequest
的两个子类)。指定网址并分别获取 JSON 对象或数组作为响应。
如果您的预期响应是这些类型之一,您可能无需实现自定义请求。本课介绍了如何使用这些标准请求类型。如需了解如何实现您自己的自定义请求,请参阅实现自定义请求。
请求 JSON
Volley 为 JSON 请求提供了以下类:
JsonArrayRequest
- 用于在给定网址检索JSONArray
响应正文的请求。JsonObjectRequest
- 用于在给定网址检索JSONObject
响应正文的请求,允许传入可选的JSONObject
作为请求正文的一部分。
这两个类均基于通用基类 JsonRequest
。您可以遵循针对其他请求类型使用的同一基本模式来使用这两个类。例如,以下代码段提取了 JSON Feed 并在界面中将其显示为文本:
Kotlin
val url = "http://my-json-feed" val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response -> textView.text = "Response: %s".format(response.toString()) }, Response.ErrorListener { error -> // TODO: Handle error } ) // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
Java
String url = "http://my-json-feed"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { textView.setText("Response: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO: Handle error } }); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);