了解如何使用 Cronet 库在您的 Android 应用。Cronet 是作为库提供的 Chromium 网络堆栈 供您在应用中使用如需详细了解库功能 请参阅使用 Cronet。
在您的项目中设置库
要在您的项目中为 Cronet 库添加依赖项,请按以下步骤操作:
验证 Android Studio 是否包含对 Google Maven 制品库的引用 在项目的
settings.gradle
文件中,如下所示 示例:Groovy
dependencyResolutionManagement { ... repositories { ... google() } }
Kotlin
dependencyResolutionManagement { ... repositories { ... google() } }
添加对适用于 Cronet 的 Google Play 服务客户端库的引用 在应用模块的
build.gradle
文件的dependencies
部分中,如下所示: 如以下示例中所示:Groovy
dependencies { implementation 'com.google.android.gms:play-services-cronet:18.0.1' }
Kotlin
dependencies { implementation("com.google.android.gms:play-services-cronet:18.0.1") }
创建过 CronetEngine
个对象
依赖项时,将使用从 Google Play 服务加载的 Cronet。致电
CronetProviderInstaller.installProvider(Context)
然后再创建 CronetEngine
对象以防止意外异常
因设备等错误而在 CronetEngine
创建期间抛出
需要更新版本的 Google Play 服务。
如果无法从 Google Play 服务加载 Cronet,
可以使用的 Cronet API 实现性能较差。要使用
此后备实现,依赖于 org.chromium.net:cronet-fallback
然后调用 new JavaCronetProvider(context).createBuilder()
。
创建网络请求
本部分介绍如何使用 Cronet 创建和发送网络请求 影视库。发送网络请求后,您的应用应处理网络 响应。
创建并配置 CronetEngine 的实例
该库提供了
CronetEngine.Builder
类
您可以用它来创建
CronetEngine
。以下示例
展示了如何创建 CronetEngine
对象:
Kotlin
val myBuilder = CronetEngine.Builder(context) val cronetEngine: CronetEngine = myBuilder.build()
Java
CronetEngine.Builder myBuilder = new CronetEngine.Builder(context); CronetEngine cronetEngine = myBuilder.build();
您可以使用 Builder
类来配置
CronetEngine
对象,例如
提供缓存和数据压缩等选项如需了解详情,请参阅
CronetEngine.Builder
。
提供请求回调的实现
要提供回调的实现,请创建
UrlRequest.Callback
和
实现所需的抽象方法,如以下示例所示:
Kotlin
private const val TAG = "MyUrlRequestCallback" class MyUrlRequestCallback : UrlRequest.Callback() { override fun onRedirectReceived(request: UrlRequest?, info: UrlResponseInfo?, newLocationUrl: String?) { Log.i(TAG, "onRedirectReceived method called.") // You should call the request.followRedirect() method to continue // processing the request. request?.followRedirect() } override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) { Log.i(TAG, "onResponseStarted method called.") // You should call the request.read() method before the request can be // further processed. The following instruction provides a ByteBuffer object // with a capacity of 102400 bytes for the read() method. The same buffer // with data is passed to the onReadCompleted() method. request?.read(ByteBuffer.allocateDirect(102400)) } override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) { Log.i(TAG, "onReadCompleted method called.") // You should keep reading the request until there's no more data. byteBuffer.clear() request?.read(byteBuffer) } override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) { Log.i(TAG, "onSucceeded method called.") } }
Java
class MyUrlRequestCallback extends UrlRequest.Callback { private static final String TAG = "MyUrlRequestCallback"; @Override public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) { Log.i(TAG, "onRedirectReceived method called."); // You should call the request.followRedirect() method to continue // processing the request. request.followRedirect(); } @Override public void onResponseStarted(UrlRequest request, UrlResponseInfo info) { Log.i(TAG, "onResponseStarted method called."); // You should call the request.read() method before the request can be // further processed. The following instruction provides a ByteBuffer object // with a capacity of 102400 bytes for the read() method. The same buffer // with data is passed to the onReadCompleted() method. request.read(ByteBuffer.allocateDirect(102400)); } @Override public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) { Log.i(TAG, "onReadCompleted method called."); // You should keep reading the request until there's no more data. byteBuffer.clear(); request.read(byteBuffer); } @Override public void onSucceeded(UrlRequest request, UrlResponseInfo info) { Log.i(TAG, "onSucceeded method called."); } }
创建一个 Executor 对象来管理网络任务
您可以使用 Executor
类来执行网络
任务。
如需获取 Executor
的实例,请使用以下任一
返回 Executors
类的静态方法
Executor
对象。以下示例展示了如何创建 Executor
对象(使用 newSingleThreadExecutor()
)
方法:
Kotlin
val executor: Executor = Executors.newSingleThreadExecutor()
Java
Executor executor = Executors.newSingleThreadExecutor();
创建并配置 UrlRequest 对象
要创建网络请求,请调用
newUrlRequestBuilder()
CronetEngine
的相应方法,用于传递
目标网址、回调类的实例以及执行器对象。
newUrlRequestBuilder()
方法会返回一个
UrlRequest.Builder
对象,
可用于创建 UrlRequest
,
对象,如以下示例所示:
Kotlin
val requestBuilder = cronetEngine.newUrlRequestBuilder( "https://www.example.com", MyUrlRequestCallback(), executor ) val request: UrlRequest = requestBuilder.build()
Java
UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder( "https://www.example.com", new MyUrlRequestCallback(), executor); UrlRequest request = requestBuilder.build();
您可以使用 Builder
类执行以下操作:
配置 UrlRequest
的实例。对于
例如,您可以指定优先级或 HTTP 动词如需了解详情,请参阅
UrlRequest.Builder
。
要启动网络任务,请调用
start()
方法:
Kotlin
request.start()
Java
request.start();
您可以按照本部分中的说明创建和发送网络
使用 Cronet 请求。不过,为简单起见,此示例
实施
只有 UrlRequest.Callback
可打印
向日志发送一条消息。以下部分介绍了如何提供回调
一种更实用的实现方式,
响应并检测请求失败的情况。
处理网络响应
调用 start()
之后,
方法,便会启动 Cronet 请求生命周期。您的应用应管理
请求。如需详细了解
请参阅 Cronet 请求
生命周期。您可以指定
通过创建
UrlRequest.Callback
和
实现以下方法:
onRedirectReceived()
在服务器发出 HTTP 重定向代码以响应 原始请求。要按照重定向到达新的目的地,请使用
followRedirect()
方法。否则,请使用cancel()
方法。以下示例展示了如何实现该方法:Kotlin
override fun onRedirectReceived(request: UrlRequest?, info: UrlResponseInfo?, newLocationUrl: String?) { // Determine whether you want to follow the redirect. ... if (shouldFollow) { request?.followRedirect() } else { request?.cancel() } }
Java
@Override public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) { // Determine whether you want to follow the redirect. … if (shouldFollow) { request.followRedirect(); } else { request.cancel(); } }
onResponseStarted()
在收到最后一组标头时调用。
onResponseStarted()
方法仅在遵循所有重定向后调用。以下代码 显示了该方法的示例实现:Kotlin
override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) { val httpStatusCode = info?.httpStatusCode if (httpStatusCode == 200) { // The request was fulfilled. Start reading the response. request?.read(myBuffer) } else if (httpStatusCode == 503) { // The service is unavailable. You should still check if the request // contains some data. request?.read(myBuffer) } responseHeaders = info?.allHeaders }
Java
@Override public void onResponseStarted(UrlRequest request, UrlResponseInfo info) { int httpStatusCode = info.getHttpStatusCode(); if (httpStatusCode == 200) { // The request was fulfilled. Start reading the response. request.read(myBuffer); } else if (httpStatusCode == 503) { // The service is unavailable. You should still check if the request // contains some data. request.read(myBuffer); } responseHeaders = info.getAllHeaders(); }
onReadCompleted()
在读取部分响应正文后调用。以下代码 示例显示了如何实现 方法并提取响应正文:
Kotlin
override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) { // The response body is available, process byteBuffer. ... // Continue reading the response body by reusing the same buffer // until the response has been completed. byteBuffer?.clear() request?.read(myBuffer) }
Java
@Override public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) { // The response body is available, process byteBuffer. … // Continue reading the response body by reusing the same buffer // until the response has been completed. byteBuffer.clear(); request.read(myBuffer); }
onSucceeded()
在网络请求成功完成后调用。以下 示例显示了如何实现该方法:
Kotlin
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) { // The request has completed successfully. }
Java
@Override public void onSucceeded(UrlRequest request, UrlResponseInfo info) { // The request has completed successfully. }
onFailed()
如果请求由于在 调用了
start()
方法。通过 以下示例展示了如何实现该方法并获取 错误:Kotlin
override fun onFailed(request: UrlRequest?, info: UrlResponseInfo?, error: CronetException?) { // The request has failed. If possible, handle the error. Log.e(TAG, "The request failed.", error) }
Java
@Override public void onFailed(UrlRequest request, UrlResponseInfo info, CronetException error) { // The request has failed. If possible, handle the error. Log.e(TAG, "The request failed.", error); }
onCanceled()
如果使用
cancel()
方法。调用之后,不会 其他方法UrlRequest.Callback
类 调用。您可以使用此方法释放分配给处理 请求。以下示例展示了如何实现该方法:Kotlin
override fun onCanceled(request: UrlRequest?, info: UrlResponseInfo?) { // Free resources allocated to process this request. ... }
Java
@Override public void onCanceled(UrlRequest request, UrlResponseInfo info) { // Free resources allocated to process this request. … }