Gửi một yêu cầu đơn giản

Tìm hiểu cách sử dụng Thư viện Cronet để thực hiện các thao tác mạng trong ứng dụng Android. Cronet là bộ phần cứng và phần mềm mạng Chromium được cung cấp dưới dạng thư viện để bạn sử dụng trong ứng dụng của mình. Để biết thêm thông tin về các tính năng của thư viện, hãy xem bài viết Thực hiện các thao tác mạng bằng Cronet.

Thiết lập thư viện trong dự án của bạn

Làm theo các bước sau để thêm phần phụ thuộc vào Thư viện Cronet trong dự án của bạn:

  1. Xác minh rằng Android Studio đã thêm thông tin tham chiếu đến Kho lưu trữ Maven của Google trong tệp settings.gradle của dự án, như trong ví dụ sau:

    Groovy

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

    Kotlin

    dependencyResolutionManagement {
       ...
       repositories {
           ...
           google()
       }
    }
  2. Thêm tệp tham chiếu đến Thư viện ứng dụng của Dịch vụ Google Play cho Cronet trong phần dependencies của tệp build.gradle trên mô-đun ứng dụng, như trong ví dụ sau:

    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")
    }

Các đối tượng CronetEngine được tạo sau khi bạn thêm phần phụ thuộc này sẽ sử dụng Cronet được tải từ Dịch vụ Google Play. Để ngăn chặn các ngoại lệ không mong muốn trong quá trình tạo CronetEngine (chẳng hạn như trên các thiết bị yêu cầu phiên bản cập nhật của Dịch vụ Google Play), hãy gọi CronetProviderInstaller.installProvider(Context) trước khi tạo đối tượng CronetEngine.

Trong trường hợp không thể tải Cronet từ Dịch vụ Google Play, bạn có thể sử dụng một cách triển khai API của Cronet có hiệu suất thấp hơn. Để sử dụng phương thức triển khai dự phòng này, hãy dựa vào org.chromium.net:cronet-fallback và gọi new JavaCronetProvider(context).createBuilder().

Tạo yêu cầu mạng

Phần này trình bày cách tạo và gửi yêu cầu mạng bằng Thư viện Cronet. Sau khi gửi yêu cầu mạng, ứng dụng của bạn phải xử lý phản hồi mạng.

Tạo và định cấu hình một thực thể của CronetEngine

Thư viện này cung cấp một lớp CronetEngine.Builder mà bạn có thể dùng để tạo một thực thể của CronetEngine. Ví dụ sau đây cho thấy cách tạo đối tượng CronetEngine:

Kotlin

val myBuilder = CronetEngine.Builder(context)
val cronetEngine: CronetEngine = myBuilder.build()

Java

CronetEngine.Builder myBuilder = new CronetEngine.Builder(context);
CronetEngine cronetEngine = myBuilder.build();

Bạn có thể sử dụng lớp Builder để định cấu hình đối tượng CronetEngine. Ví dụ: bạn có thể cung cấp các lựa chọn như lưu vào bộ nhớ đệm và nén dữ liệu. Để biết thêm thông tin, hãy xem CronetEngine.Builder.

Cung cấp cách triển khai lệnh gọi lại yêu cầu

Để triển khai lệnh gọi lại, hãy tạo một lớp con của UrlRequest.Callback và triển khai các phương thức trừu tượng bắt buộc, như trong ví dụ sau:

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.");
  }
}

Tạo đối tượng Executor để quản lý các tác vụ mạng

Bạn có thể sử dụng lớp Executor để chạy các tác vụ mạng. Để lấy một thực thể của Executor, hãy sử dụng một trong các phương thức tĩnh của lớp Executors trả về đối tượng Executor. Ví dụ sau đây cho thấy cách tạo đối tượng Executor bằng phương thức newSingleThreadExecutor():

Kotlin

val executor: Executor = Executors.newSingleThreadExecutor()

Java

Executor executor = Executors.newSingleThreadExecutor();

Tạo và định cấu hình đối tượng UrlRequest

Để tạo yêu cầu mạng, hãy gọi phương thức newUrlRequestBuilder() của CronetEngine truyền URL đích, một thực thể của lớp gọi lại và đối tượng trình thực thi. Phương thức newUrlRequestBuilder() trả về một đối tượng UrlRequest.Builder mà bạn có thể dùng để tạo đối tượng UrlRequest, như trong ví dụ sau:

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();

Bạn có thể sử dụng lớp Builder để định cấu hình thực thể của UrlRequest. Ví dụ: bạn có thể chỉ định mức độ ưu tiên hoặc động từ HTTP. Để biết thêm thông tin, hãy xem UrlRequest.Builder.

Để bắt đầu tác vụ mạng, hãy gọi phương thức start() của yêu cầu:

Kotlin

request.start()

Java

request.start();

Bằng cách làm theo hướng dẫn trong phần này, bạn có thể tạo và gửi yêu cầu mạng bằng Cronet. Tuy nhiên, để đơn giản, ví dụ về cách triển khai UrlRequest.Callback chỉ in một thông báo vào nhật ký. Phần sau đây trình bày cách cung cấp một phương thức triển khai lệnh gọi lại hỗ trợ các trường hợp hữu ích hơn, chẳng hạn như trích xuất dữ liệu từ phản hồi và phát hiện lỗi trong yêu cầu.

Xử lý phản hồi mạng

Sau khi bạn gọi phương thức start(), Cronet sẽ bắt đầu vòng đời của yêu cầu. Quản lý yêu cầu trong vòng đời bằng cách chỉ định một lệnh gọi lại. Để biết thêm thông tin về vòng đời, hãy xem phần Vòng đời của yêu cầu Cronet. Bạn có thể chỉ định một lệnh gọi lại bằng cách tạo một lớp con của UrlRequest.Callback và triển khai các phương thức sau:

onRedirectReceived()

Cronet gọi phương thức này khi máy chủ phát hành mã chuyển hướng HTTP để phản hồi yêu cầu ban đầu. Để làm theo lệnh chuyển hướng đến đích đến mới, hãy sử dụng phương thức followRedirect(). Nếu không, hãy sử dụng phương thức cancel(). Ví dụ sau đây cho thấy cách triển khai phương thức:

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()

Cronet gọi phương thức này khi nhận được tập hợp tiêu đề cuối cùng. Cronet chỉ gọi onResponseStarted() sau khi tất cả lệnh chuyển hướng được thực hiện. Đoạn mã sau đây cho thấy ví dụ về cách triển khai phương thức này:

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()

Cronet gọi phương thức này bất cứ khi nào một phần nội dung phản hồi được đọc. Đoạn mã ví dụ sau đây cho thấy cách triển khai phương thức và trích xuất nội dung phản hồi:

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()

Cronet gọi phương thức này khi yêu cầu mạng hoàn tất thành công. Ví dụ sau đây cho thấy cách triển khai phương thức:

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()

Cronet gọi phương thức này nếu yêu cầu không thành công vì bất kỳ lý do nào sau khi ứng dụng của bạn gọi phương thức start(). Ví dụ sau đây cho thấy cách triển khai phương thức và lấy thông tin về lỗi:

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()

Cronet gọi phương thức này nếu yêu cầu bị huỷ bằng phương thức cancel(). Sau khi gọi onCanceled(), Cronet sẽ không gọi bất kỳ phương thức nào khác của lớp UrlRequest.Callback. Bạn có thể sử dụng phương thức này để giải phóng tài nguyên được phân bổ nhằm xử lý một yêu cầu. Ví dụ sau đây cho thấy cách triển khai phương thức:

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.
  ...
}