Жизненный цикл запроса Cronet
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Узнайте о жизненном цикле запросов, созданных с помощью Cronet, и о том, как управлять ими с помощью методов обратного вызова, предоставляемых библиотекой.
Обзор жизненного цикла
Сетевые запросы, созданные с помощью библиотеки Cronet, представлены классом UrlRequest
. Следующие понятия важны для понимания жизненного цикла UrlRequest
:
- Штаты
- Состояние — это особое состояние, в котором находится запрос в определенное время. Объекты UrlRequest, созданные с использованием библиотеки Cronet, в своем жизненном цикле проходят разные состояния. Жизненный цикл запроса включает начальное состояние, а также несколько переходных и конечных состояний.
- Методы
UrlRequest
- Клиенты могут вызывать определенные методы объектов
UrlRequest
в зависимости от состояния. Методы переводят запрос из одного состояния в другое. - Методы
Callback
- Реализуя методы класса
UrlRequest.Callback
, ваше приложение может получать обновления о ходе выполнения запроса. Вы можете реализовать методы обратного вызова для вызова методов объекта UrlRequest
, которые переводят жизненный цикл из одного состояния в другое.
В следующем списке описан поток жизненного цикла UrlRequest
:
- Жизненный цикл находится в состоянии «Начало» после того, как ваше приложение вызывает метод
start()
. - Сервер может отправить ответ о перенаправлении, который передает поток методу
onRedirectReceived()
. В этом методе вы можете выполнить одно из следующих действий клиента:- Следуйте за перенаправлением, используя
followRedirect()
. Этот метод возвращает запрос в состояние «Начало» . - Отмените запрос с помощью
cancel()
. Этот метод передает запрос в метод onCanceled()
, где приложение может выполнять дополнительные операции, прежде чем запрос будет переведен в конечное состояние «Отменено» .
- После того как приложение выполняет все перенаправления, сервер отправляет заголовки ответа и вызывается метод
onResponseStarted()
. Запрос находится в состоянии Ожидание чтения() . Приложение должно вызвать метод read()
, чтобы попытаться прочитать часть тела ответа. После вызова read()
запрос находится в состоянии чтения , где возможны следующие результаты:- Действие чтения прошло успешно, но доступно больше данных. Вызывается
onReadCompleted()
, и запрос снова находится в состоянии ожидания чтения() . Приложению следует снова вызвать метод read()
, чтобы продолжить чтение тела ответа. Приложение также может прекратить чтение запроса с помощью метода cancel()
. - Действие чтения прошло успешно, и доступных данных больше нет. Вызывается метод
onSucceeded()
, и запрос теперь находится в конечном состоянии «Успешно» . - Действие чтения не удалось. Вызывается метод
onFailed
, и окончательное состояние запроса теперь Failed .
На следующей диаграмме показан жизненный цикл объекта UrlRequest
:

Жизненный цикл запроса Cronet
Легенда | |
---|
исходное состояние | конечное состояние |
переходное состояние | методы обратного вызова |
Методы UrlRequest | |
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 UTC.
[null,null,["Последнее обновление: 2025-07-29 UTC."],[],[],null,["# Cronet request lifecycle\n\nLearn about the lifecycle of requests created using Cronet and how to manage\nthem using the callback methods provided by the library.\n\nLifecycle overview\n------------------\n\nNetwork requests created using the Cronet Library are represented by the\n[`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) class.\nThe following concepts are important to understand the\n[`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) lifecycle:\n\n**States**\n: A state is the particular condition that the request is in at a specific time.\n [UrlRequest](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) objects created using the Cronet\n Library move through different states in their lifecycle. The request\n lifecycle includes an initial state, and multiple transitional and final\n states.\n\n**`UrlRequest` methods**\n: Clients can call specific methods on\n [`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) objects depending on the\n state. The methods move the request from one state to another.\n\n**`Callback` methods**\n: By implementing methods of the\n [`UrlRequest.Callback`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback) class, your\n app can receive updates about the progress of the request. You can implement\n the callback methods to call methods of the\n [`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) object that take the lifecycle\n from a state to another.\n\nThe following list describes the flow of the\n[`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) lifecycle:\n\n1. The lifecycle is in the **Started** state after your app calls the [`start()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#start()) method.\n2. The server could send a redirect response, which takes the flow to the [`onRedirectReceived()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onRedirectReceived(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo,%20java.lang.String)) method. In this method, you can take one of the following client actions:\n - Follow the redirect using [`followRedirect()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#followRedirect()). This method takes the request back to the **Started** state.\n - Cancel the request using [`cancel()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#cancel()). This method takes the request to the [`onCanceled()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onCanceled(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo)) method where the app can perform additional operations before the request is moved to the **Canceled** final state.\n3. After the app follows all the redirects, the server sends the response headers and the [`onResponseStarted()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onResponseStarted(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo)) method is called. The request is in the **Waiting for read()** state. The app should call the [`read()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#read(java.nio.ByteBuffer)) method to attempt to read part of the response body. After `read()` is called, the request is in the **Reading** state, where there are the following possible outcomes:\n - The reading action was successful, but there is more data available. The [`onReadCompleted()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onReadCompleted(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo,%20java.nio.ByteBuffer)) is called and the request is in the **Waiting for read()** state again. The app should call the [`read()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#read(java.nio.ByteBuffer)) method again to continue reading the response body. The app could also stop reading the request by using the [`cancel()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest#cancel()) method .\n - The reading action was successful, and there is no more data available. The [`onSucceeded()`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onSucceeded(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo)) method is called and the request is now in the **Succeeded** final state.\n - The reading action failed. The [`onFailed`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback#onFailed(org.chromium.net.UrlRequest,%20org.chromium.net.UrlResponseInfo,%20org.chromium.net.CronetException)) method is called and the final state of the request is now **Failed**.\n\nThe following diagram shows the lifecycle of a\n[`UrlRequest`](/develop/connectivity/cronet/reference/org/chromium/net/UrlRequest) object:\n\n\u003cbr /\u003e\n\n\nThe Cronet request lifecycle\n\n| Legend | |\n|----------------------|------------------|\n| initial state | final state |\n| transitional state | callback methods |\n| `UrlRequest` methods | |"]]