傳送簡單的要求

瞭解如何使用 Cronet 程式庫,在 Android 應用程式。Cronet 是 Chromium 網路堆疊的程式庫 方便你在應用程式中使用如要進一步瞭解程式庫功能 請參閱使用 Cronet

在專案中設定程式庫

請按照下列步驟,將依附元件新增至專案的 Cronet 程式庫:

  1. 確認 Android Studio 含有 Google 的 Maven 存放區參照 ,如下所示settings.gradle 範例:

    Groovy

    dependencyResolutionManagement {
       ...
       repositories {
           ...
           google()
       }
    }
    

    Kotlin

    dependencyResolutionManagement {
       ...
       repositories {
           ...
           google()
       }
    }
    
  2. 加入 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();

按照本節的操作說明,即可建立及傳送網路 提出要求。不過,為了方便起見 實作 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.
  
}