跳转到相应内容

最常访问

最近访问

navigation

Implementing a Custom Request

This lesson teaches you to

  1. Write a Custom Request

Video

Volley: Easy, Fast Networking for Android

This lesson describes how to implement your own custom request types, for types that don't have out-of-the-box Volley support.

Write a Custom Request

Most requests have ready-to-use implementations in the toolbox; if your response is a string, image, or JSON, you probably won't need to implement a custom Request.

For cases where you do need to implement a custom request, this is all you need to do:

parseNetworkResponse

A Response encapsulates a parsed response for delivery, for a given type (such as string, image, or JSON). Here is a sample implementation of parseNetworkResponse():

Kotlin

override fun parseNetworkResponse(response: NetworkResponse?): Response<T> {
    return try {
        val json = String(
                response?.data ?: ByteArray(0),
                Charset.forName(HttpHeaderParser.parseCharset(response?.headers)))
        Response.success(
                gson.fromJson(json, clazz),
                HttpHeaderParser.parseCacheHeaders(response))
    }
    // handle errors
// ...
}

Java

@Override
protected Response<T> parseNetworkResponse(
        NetworkResponse response) {
    try {
        String json = new String(response.data,
        HttpHeaderParser.parseCharset(response.headers));
    return Response.success(gson.fromJson(json, clazz),
    HttpHeaderParser.parseCacheHeaders(response));
    }
    // handle errors
// ...
}

Note the following:

If your protocol has non-standard cache semantics, you can build a Cache.Entry yourself, but most requests are fine with something like this:

Kotlin

return Response.success(myDecodedObject,
        HttpHeaderParser.parseCacheHeaders(response))

Java

return Response.success(myDecodedObject,
        HttpHeaderParser.parseCacheHeaders(response));

Volley calls parseNetworkResponse() from a worker thread. This ensures that expensive parsing operations, such as decoding a JPEG into a Bitmap, don't block the UI thread.

deliverResponse

Volley calls you back on the main thread with the object you returned in parseNetworkResponse(). Most requests invoke a callback interface here, for example:

Kotlin

override fun deliverResponse(response: T) = listener.onResponse(response)

Java

protected void deliverResponse(T response) {
        listener.onResponse(response);

Example: GsonRequest

Gson is a library for converting Java objects to and from JSON using reflection. You can define Java objects that have the same names as their corresponding JSON keys, pass Gson the class object, and Gson will fill in the fields for you. Here's a complete implementation of a Volley request that uses Gson for parsing:

Kotlin

/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url URL of the request to make
 * @param clazz Relevant class object, for Gson's reflection
 * @param headers Map of request headers
 */
class GsonRequest<T>(
        url: String,
        private val clazz: Class<T>,
        private val headers: MutableMap<String, String>?,
        private val listener: Response.Listener<T>,
        errorListener: Response.ErrorListener
) : Request<T>(Method.GET, url, errorListener) {
    private val gson = Gson()


    override fun getHeaders(): MutableMap<String, String> = headers ?: super.getHeaders()

    override fun deliverResponse(response: T) = listener.onResponse(response)

    override fun parseNetworkResponse(response: NetworkResponse?): Response<T> {
        return try {
            val json = String(
                    response?.data ?: ByteArray(0),
                    Charset.forName(HttpHeaderParser.parseCharset(response?.headers)))
            Response.success(
                    gson.fromJson(json, clazz),
                    HttpHeaderParser.parseCacheHeaders(response))
        } catch (e: UnsupportedEncodingException) {
            Response.error(ParseError(e))
        } catch (e: JsonSyntaxException) {
            Response.error(ParseError(e))
        }
    }
}

Java

public class GsonRequest<T> extends Request<T> {
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */
    public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
            Listener<T> listener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

Volley provides ready-to-use JsonArrayRequest and JsonArrayObject classes if you prefer to take that approach. See Using Standard Request Types for more information.

此网站会使用 Cookie 来存储您在此网站上指定的语言和显示选项偏好设置。

获取最新的 Android Developers 资讯和提示,助您在 Google Play 上取得成功。

* 必填字段

成功!

在微信上关注 Google Developers

要以浏览此网站吗?

您请求访问的是网页,但是您为此网站设置的语言偏好为

要更改您的语言偏好设置并以浏览此网站吗?如果以后您想要更改语言偏好设置,请使用每个页面底部的语言菜单。

该类需要 或更高的 API 级别

此文档已被隐藏,因为您为该文档选择的 API 级别是 。您可以使用左侧导航栏上方的选择器来更改文档的 API 级别。

要详细了解如何根据您的应用需求指定 API 级别,请参阅支持不同平台版本

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)